Skip to content

Instantly share code, notes, and snippets.



Created Nov 11, 2016
What would you like to do?
{-# LANGUAGE MultiParamTypeClasses #-}
import Text.Printf
data Hello = Hello
data Goodbye = Goodbye
data Teacher = Teacher String
data Friend = Friend String
class Say a b where
say :: a -> b -> IO ()
instance Say Hello Teacher where
say _ (Teacher name) = printf "こんにちは。%s先生\n" name
instance Say Hello Friend where
say _ (Friend name) = printf "やあ %s\n" name
instance Say Goodbye Teacher where
say _ (Teacher name) = printf "%s先生、さようなら\n" name
instance Say Goodbye Friend where
say _ (Friend name) = printf "またね %s\n" name
main = do
say Hello (Teacher "にゃんこ")
say Hello (Friend "モンティ")
say Goodbye (Teacher "にゃんこ")
say Goodbye (Friend "モンティ")
from __future__ import print_function
class HelloTeacher:
def __init__(self, name): = name
def say(self):
print("こんにちは。%s先生" %
class HelloFriend:
def __init__(self, name): = name
def say(self):
print("やあ %s" %
class GoodbyeTeacher:
def __init__(self, name): = name
def say(self):
print("%s先生、さようなら" %
class GoodebyeFriend:
def __init__(self, name): = name
def say(self):
print("またね %s" %
def say(self):
case class Hello()
case class Goodbye()
case class Teacher(name: String)
case class Friend(name: String)
// 呼び出すためのインターフェイス
trait Say[A, B] {
def say(a: A, b: B): Unit
// 分岐を自動生成するための場所
object Say{
def say[A, B](a: A, b: B)(implicit obj: Say[A, B]) = {
// 実際の動作
object SayOps {
implicit val helloTeacherSay: Say[Hello, Teacher] = new Say[Hello, Teacher] {
def say(self: Hello, target: Teacher): Unit = {
implicit val helloFriedSay: Say[Hello, Friend] = new Say[Hello, Friend] {
def say(self: Hello, target: Friend): Unit = {
println(s"やあ ${}")
implicit val goodbyeTeacherSay: Say[Goodbye, Teacher] = new Say[Goodbye, Teacher] {
def say(self: Goodbye, target: Teacher): Unit = {
implicit val goodbyeFriendSay: Say[Goodbye, Friend] = new Say[Goodbye, Friend] {
def say(self: Goodbye, target: Friend): Unit = {
println(s"またね ${}")
object Main extends App {
import Say.say
import SayOps._
say(Hello(), Teacher("にゃんこ")) // おはようございます。にゃんこ先生
say(Hello(), Friend("モンティ")) // やあ モンティ
say(Goodbye(), Teacher("にゃんこ")) // にゃんこ先生、さようなら
say(Goodbye(), Friend("モンティ")) // またね モンティ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment