Last active
August 29, 2015 14:03
-
-
Save takkkun/fa65c640cbd963787f5f 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
trait FlipFlap[A, B] { | |
def doFlipFlap(x: A): B | |
} | |
class FlipFlapOps[A, B](v: A, f: FlipFlap[A, B]) { | |
def flipFlap = f.doFlipFlap(v) | |
} | |
object Main { | |
implicit def intFlipFlap = new FlipFlap[Int, Int] { | |
def doFlipFlap(x: Int) = -x | |
} | |
implicit def stringFlipFlap = new FlipFlap[String, String] { | |
def doFlipFlap(x: String) = x.reverse | |
} | |
implicit def pairListFlipFlap[A1, A2] = new FlipFlap[List[Pair[A1, A2]], List[Pair[A2, A1]]] { | |
def doFlipFlap(x: List[Pair[A1, A2]]) = x.map(_.swap) | |
} | |
implicit def mapFlipFlap[K, V] = new FlipFlap[Map[K, V], Map[V, K]] { | |
def doFlipFlap(x: Map[K, V]) = Map() ++ x.map(_.swap) | |
} | |
implicit def toAnyFlipFlapWrapper[A](value: A)(implicit implicitFlipFlap: FlipFlap[A, A]) = | |
new FlipFlapOps(value, implicitFlipFlap) | |
implicit def toPairListFlipFlapWrapper[A1, A2](value: List[Pair[A1, A2]])(implicit implicitFlipFlap: FlipFlap[List[Pair[A1, A2]], | |
List[Pair[A2, A1]]]) = | |
new FlipFlapOps(value, implicitFlipFlap) | |
implicit def toMapFlipFlapWrapper[K, V](value: Map[K, V])(implicit implicitFlipFlap: FlipFlap[Map[K, V], Map[V, K]]) = | |
new FlipFlapOps(value, implicitFlipFlap) | |
def main(args: Array[String]) { | |
println(1.flipFlap) | |
println("hello".flipFlap) | |
println(List(1 -> 2, 3 -> 4).flipFlap) | |
println(List(1, 2).flipFlap) // Compiling error | |
println(Map( | |
"Dog" -> "Wan", | |
"Cat" -> "Nyan" | |
).flipFlap) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment