Skip to content

Instantly share code, notes, and snippets.

@sofoklis
Last active December 11, 2015 19:38
Show Gist options
  • Save sofoklis/4649849 to your computer and use it in GitHub Desktop.
Save sofoklis/4649849 to your computer and use it in GitHub Desktop.
lifted options
// A lift function that takes a regular function that cannot handle options
// and uses for to call it only with Some(...) cases
def lift1[A, B](f: Function1[A, B]): Function1[Option[A], Option[B]] = {
(oa: Option[A]) =>
for (a <- oa) yield f(a)
} //> lift1: [A, B](f: A => B)Option[A] => Option[B]
// Same for a 2 argument function, if any of the arguments is None, the function simply returns None
def lift2[A, B, C, D](f: Function2[A, B, C]): Function2[Option[A], Option[B], Option[C]] = {
(oa: Option[A], ob: Option[B]) =>
for (a <- oa; b <- ob) yield f(a, b)
} //> lift2: [A, B, C, D](f: (A, B) => C)(Option[A], Option[B]) => Option[C]
def strCountChars(value: String) = value.length //> strCountChars: (value: String)Int
def strCountChars2(value1: String, value2: String) = value1.length + value2.length
//> strCountChars2: (value1: String, value2: String)Int
//strCountChars(null) // this will give a null pointer error
// Lift the 1 argument function into its optionable version
val liftedCountChars = lift1(strCountChars) //> liftedCountChars : Option[String] => Option[Int] = <function1>
// Lift the 2 argument function into its optionable version
val liftedCountChars2 = lift2(strCountChars2) //> liftedCountChars2 : (Option[String], Option[String]) => Option[Int] = <function2>
liftedCountChars(Option(null)) //> res0: Option[Int] = None
liftedCountChars(Option("Something")) //> res1: Option[Int] = Some(9)
liftedCountChars2(Option(null), Option("Something")) //> res1: Option[Int] = None
liftedCountChars2(Option("Something"), Option(null)) //> res2: Option[Int] = None
liftedCountChars2(Option("Something"), Option("Good")) //> res3: Option[Int] = Some(13)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment