I successfully implemented the following curried function using flatMap
:
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) ) ) )
}
Example:
scala> map3(Some(1), Some(2), Some(3))( (x,y,z) => Some(x*y*z) )
res0: Option[Int] = Some(6)
However, when I tried to implement the same function with a for expression
:
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 <- b
f(x,y,z)
}
}
... the following compile-time error occurred:
C:\Users\Kevin\Workspace\side-work>scalac TestForComprehensionMap3.scala TestForComprehensionMap3.scala:13: error: '<-' expected but '}' found. } ^
Based on reading this excellent post, it seems to me that my map3ForExpr
is equivalent to my map3
code.
Please let me know what I'm doing wrong.