Skip to content

Instantly share code, notes, and snippets.

@douglas-vaz
Created February 9, 2018 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglas-vaz/28f9416c8c34a343d43d6f0a2c6293eb to your computer and use it in GitHub Desktop.
Save douglas-vaz/28f9416c8c34a343d43d6f0a2c6293eb to your computer and use it in GitHub Desktop.
Scala compose monadic type
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