Created
July 1, 2014 04:39
-
-
Save Shinpeim/0a438fbca7509f643273 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.language.implicitConversions | |
// FlipFlap型クラスを定義 | |
trait FlipFlap[T] { | |
// このメソッドはアドホック多相を実現する | |
def flipFlap(x: T): T | |
} | |
// Int をFlipFlap型クラスの型インスタンスとして定義 | |
implicit val intFlipFlap = new FlipFlap[Int] { | |
def flipFlap(x: Int): Int = - x | |
} | |
// String をFlipFlap型クラスのインスタンスとして定義 | |
implicit val stringFlipFlap = new FlipFlap[String] { | |
def flipFlap(x: String): String = x.reverse | |
} | |
// Boolean をFlipFlap型クラスのインスタンスとして定義 | |
implicit val booleanFlipFlap = new FlipFlap[Boolean] { | |
def flipFlap(x: Boolean): Boolean = ! x | |
} | |
// ここからは、FlipFlap型クラスのインスタンスすべての型に対して | |
// FlipFlap型が提しているアドホック多相なメソッドを生やすためにいろいろやる | |
// あるクラスを拡張する場合、Scalaでは普通implicit conversionを利用する。 | |
// それとimplicit parameter によるアドホック多相の組み合わせで、 | |
// 型クラスのインスタンスすべてのクラスを拡張できる。 | |
trait FlipFlapWrapper[A] { | |
val f:FlipFlap[A] | |
val value:A | |
def flipFlap():A = f.flipFlap(value) | |
} | |
implicit def toFlipFlapWrapper[A](v:A)(implicit implicitFlipFlap:FlipFlap[A]) = new FlipFlapWrapper[A] { | |
val value = v | |
val f = implicitFlipFlap | |
} | |
println(1.flipFlap) // => -1 | |
println("string".flipFlap) // => "gnirts" | |
println(true.flipFlap) // => "gnirts" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment