do みたいな for

Scala の for を Haskell の do みたいに使ってみる。

Haskell

f :: Maybe Int -> Maybe Int -> Maybe Int
f am bm = do
 a <- am
 b <- bm
 let c = a + b
 return (2 * c)
> f (Just 3) (Just 1)
Just 8
> f Nothing Nothing
Nothing
> f (Just 3) Nothing
Nothing
> f Nothing (Just 1)
Nothing


Scala

scala> def f(am:Option[Int], bm:Option[Int]) = for {
     |   a <- am
     |   b <- bm
     |   c = a + b
     | } yield {
     |   2 * c
     | }
f: (am: Option[Int],bm: Option[Int])Option[Int]

scala> f(Some(3),Some(1))
res0: Option[Int] = Some(8)

scala> f(None,None)
res1: Option[Int] = None

scala> f(Some(3),None)
res2: Option[Int] = None

scala> f(None,Some(1))
res3: Option[Int] = None

おー。