Created
September 15, 2012 18:56
-
-
Save tmyymmt/3729301 to your computer and use it in GitHub Desktop.
Solution for nested match statements
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
// see https://gist.github.com/2382341 | |
// scalaz for only solution3 | |
import scalaz._ | |
import Scalaz._ | |
object SolutionForMultiNestedMatchforMyStudy { | |
def f(num: Int): Option[Int] = { | |
num match { | |
case 0 => Some(1) | |
case 1 => Some(2) | |
case 2 => Some(3) | |
case _ => None | |
} | |
} | |
def solution1(num: Int): Int = { | |
f(num) match { | |
case Some(v1) => { | |
f(v1) match { | |
case Some(v2) => { | |
f(v2) match { | |
case Some(v3) => v3 | |
case _ => -3 | |
} | |
} | |
case _ => -2 | |
} | |
} | |
case _ => -1 | |
} | |
} | |
def solution2(num: Int): Int = { | |
val v1 = f(num) | |
val v2 = v1.flatMap(f) | |
val v3 = v2.flatMap(f) | |
(v1, v2, v3) match { | |
case (Some(_), Some(_), Some(result)) => result | |
case (Some(_), Some(_), None) => -3 | |
case (Some(_), None, None) => -2 | |
case _ => -1 | |
} | |
} | |
def solution3(num: Int): Int = { | |
f(num).toSuccess(-1).flatMap(f(_).toSuccess(-2)).flatMap(f(_).toSuccess(-3)).fold(identity, a => a) | |
} | |
def solution4(num: Int): Int = { | |
(for { | |
v1 <- f(num).toRight(-1).right | |
v2 <- f(v1).toRight(-2).right | |
v3 <- f(v2).toRight(-3).right | |
} yield v3).merge | |
} | |
def solution5(num: Int): Int = { | |
val v1 = f(num).getOrElse { return -1 } | |
val v2 = f(v1).getOrElse { return -2 } | |
f(v2).getOrElse { return -3 } | |
} | |
def example { | |
(0 to 3).foreach{n => println(solution1(n))} | |
println | |
(0 to 3).foreach{n => println(solution2(n))} | |
println | |
(0 to 3).foreach{n => println(solution3(n))} | |
println | |
(0 to 3).foreach{n => println(solution4(n))} | |
println | |
(0 to 3).foreach{n => println(solution5(n))} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
additional information:
Option Monad in Scala
http://xerial.org/scala-cookbook/recipes/2012/08/15/option/
http://www.youtube.com/watch?v=Mw_Jnn_Y5iA
http://boykin.wordpress.com/2011/09/11/option-monad-in-scala/