Created
February 9, 2018 14:00
-
-
Save douglas-vaz/28f9416c8c34a343d43d6f0a2c6293eb to your computer and use it in GitHub Desktop.
Scala compose monadic type
This file contains 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
implicit class OptionK[A, B](f: (A) => Option[B]) { | |
def composed[C](g: B => Option[C]): (A) => Option[C] = (x: A) => f(x).flatMap(g) | |
} | |
val strToInt:(String) => Option[Int] = s => if(s.matches("-?[\\d]+")) Some(s.toInt) else None | |
val realSqrt:(Int) => Option[Double] = x => if(x > 0) Some(Math.sqrt(x)) else None | |
val strToSqrt = strToInt composed realSqrt | |
strToSqrt("9") //Some(3.0) | |
strToSqrt("-9") //None | |
strToSqrt("meh") //None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment