Maybe/Option のリストから普通のリストへ
Ocaml の時は自作したけど、Scala と Haskell は結構簡単にできる。
scala> List(Some(4), Some(2), None, Some(9), None, Some(0)) flatMap (x => x) res0: List[Int] = List(4, 2, 9, 0)
> [Just 4, Just 2, Nothing, Just 9, Nothing, Just 0] >>= maybe [] return [4,2,9,0]
ただ、Haskell は普通に bind id しようとすると怒られる。
> [Just 4, Just 2, Nothing, Just 9, Nothing, Just 0] >>= id <interactive>:1:55: Couldn't match expected type `[b]' against inferred type `Maybe t' In the second argument of `(>>=)', namely `id' In the expression: [Just 4, Just 2, Nothing, Just 9, ....] >>= id In the definition of `it': it = [Just 4, Just 2, Nothing, ....] >>= id
for/do 構文を使っても書ける。
実際、TDDBC 名古屋初日の、自分の卓の Scala 組は for 式を上手いこと使っていた。
OCaml ももっと自由に使えるように勉強していこう。