モナドを研究しているときに、リスト定義のパターン マッチングが失敗したときに、その計算がエラーをスローする代わりに「無視」される理由を理解しました。
test :: [(Int, Int)]
test = [(x, y) | (Just x) <- [Just 1, Nothing, Just 3], y <- [1, 2]]
*Main> test
[(1,1),(1,2),(3,1),(3,2)]
これは、次を使用するアプリケーションの単なる構文糖衣であるためです。Monad
do
test'' :: [(Int, Int)]
test'' = do
(Just x) <- [Just 1, Nothing, Just 3]
y <- [1, 2]
return (x, y)
*Main> test'
[(1,1),(1,2),(3,1),(3,2)]
*Main> test == test'
True
同様に、バインド演算子 を使用して、このロジックに似せようとすることもでき>>=
ます。
test'' :: [(Int, Int)]
test'' = [Just 1, Nothing, Just 3] >>= \(Just x) -> [1, 2] >>= \y -> return (x, y)
ただし、予想どおり、この状況では、前の状況のようにモナド関数は呼び出さfail
れList
ません。
*Main> test''
[(1,1),(1,2)*** Exception: test.hs:11:40-82: Non-exhaustive patterns in lambda
だから、私の質問は、きちんとした方法でスタイルを使用することは可能ですか? このようなものの構文糖衣を構築していますか?[(1,1),(1,2),(3,1),(3,2)]
test''
do
test'' :: [(Int, Int)]
test'' = [Just 1, Nothing, Just 3] >>= \maybeX -> [1, 2] >>= \y -> case maybeX of Just x -> return (x, y)
_ -> fail undefined
*Main> test''
[(1,1),(1,2),(3,1),(3,2)]
*Main> test'' == test
True