Skip to content

Instantly share code, notes, and snippets.

@kevinmeredith
Created January 6, 2014 16:24
Show Gist options
  • Select an option

  • Save kevinmeredith/8285321 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmeredith/8285321 to your computer and use it in GitHub Desktop.
for comprehension trying to use map (rather than flatMap)
object TestForComprehensionMap3 {
def map3(a: Option[Int], b: Option[Int], c: Option[Int])(f: (Int, Int, Int) => Option[Int]): Option[Int] = {
a.flatMap(x => b.flatMap(y => c.flatMap(z => f(x,y,z) ) ) )
}
def map3ForExpr(a: Option[Int], b: Option[Int], c: Option[Int])(f: (Int, Int, Int) => Option[Int]): Option[Int] = {
for {
x <- a
y <- b
z <- c
} yield( f(x,y,z))
}
def main(args: Array[String]) {
val mapResult = map3(Some(1), Some(2), Some(3))( (x,y,z) => Some(x*y*z) )
assert(mapResult == Some(6))
val forResult = map3ForExpr(Some(1), Some(2), Some(3))( (x,y,z) => Some(x*y*z) )
assert(forResult == Some(6))
}
}
/* compile-time error:
C:\Users\Kevin\Workspace\side-work>scalac TestForComprehensionMap3.scala && scala TestForComprehensionMap3
TestForComprehensionMap3.scala:13: error: type mismatch;
found : Option[Int]
required: Int
} yield( f(x,y,z))//yield out
^
one error found
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment