Last active
December 10, 2017 06:01
-
-
Save amaya382/6489d4f6436b3f818f97b419ae7521a7 to your computer and use it in GitHub Desktop.
(dotty)
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
object Main { | |
def main(args: Array[String]): Unit = { | |
case class =>>[T, U](f: T => Boolean, g: T => U) | |
implicit class Ex[T](f: T => Boolean) { | |
def =>>[U](g: T => U): T =>> U = new =>>(f, g) | |
} | |
def matchx1[T, U](target: T)(cases: (T =>> U)*): U = { | |
cases.collectFirst { | |
case cas if cas.f(target) => cas.g(target) | |
}.get | |
} | |
val res1 = for { | |
i <- 1 to 15 | |
} yield { | |
matchx1(i)((((_: Int) % 15 == 0) =>> (_ => "FizzBuzz")), | |
(((_: Int) % 5 == 0) =>> (_ => "Buzz")), | |
(((_: Int) % 3 == 0) =>> (_ => "Fizz")), | |
(((_: Int) => true) =>> (_.toString))) | |
} | |
res1.foreach(println) | |
println("-" * 10) | |
case class Case[T, U](pattern: (T => Boolean, T => U)) | |
def casex[T, U](f: T => Boolean)(g: T => U): Case[T, U] = Case(f -> g) | |
def matchx2[T, U](target: T)(cases: Case[T, U]*): U = { | |
cases.collectFirst { | |
case cas if cas.pattern._1(target) => cas.pattern._2(target) | |
}.get | |
} | |
val res2 = for { | |
i <- 1 to 15 | |
} yield { | |
matchx2(i)(Case(((_: Int) % 15 == 0) -> (_ => "FizzBuzz")), | |
Case(((_: Int) % 5 == 0) -> (_ => "Fizz")), | |
Case(((_: Int) % 3 == 0) -> (_ => "Buzz")), | |
Case(((_: Int) => true) -> (_.toString))) | |
} | |
res2.foreach(println) | |
println("-" * 10) | |
val res3 = for { | |
i <- 1 to 15 | |
} yield { | |
matchx2(i)(casex((_: Int) % 15 == 0)(_ => "FizzBuzz"), | |
casex((_: Int) % 5 == 0)(_ => "Fizz"), | |
casex((_: Int) % 3 == 0)(_ => "Buzz"), | |
casex((_: Int) => true)(_.toString)) | |
} | |
res3.foreach(println) | |
println("-" * 10) | |
def matchx3[T, U](target: T)(cases: Case[T, U]*): Option[U] = { | |
cases.collectFirst { | |
case cas if cas.pattern._1(target) => cas.pattern._2(target) | |
} | |
} | |
val res4 = for { | |
i <- 1 to 15 | |
j <- matchx3(i)(Case(((_: Int) % 15 == 0) -> (_ => "FizzBuzz")), | |
Case(((_: Int) % 5 == 0) -> (_ => "Fizz")), | |
Case(((_: Int) % 3 == 0) -> (_ => "Buzz")), | |
Case(((_: Int) => true) -> (_.toString))) | |
} yield j | |
res4.foreach(println) | |
println("-" * 10) | |
def matchx[T, U](target: T)(cases: (T => Boolean, T => U)*): U = { | |
cases.collectFirst { | |
case cas if cas._1(target) => cas._2(target) | |
}.get | |
} | |
val res = for { | |
i <- 1 to 15 | |
} yield { | |
matchx(i)((((_: Int) % 15 == 0) -> (_ => "FizzBuzz")), | |
(((_: Int) % 5 == 0) -> (_ => "Buzz")), | |
(((_: Int) % 3 == 0) -> (_ => "Fizz")), | |
(((_: Int) => true) -> (_.toString))) | |
} | |
res.foreach(println) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment