foldM
定義
code:hs
foldlM :: (Foldable t, Monad m) => (b -> a -> m b) -> b -> t a -> m b
foldlM f z0 xs = foldr f' return xs z0
where f' x k z = f z x >>= k
tを具体化して、もっとわかりやすく書くと
code:hs
foldlM :: (Monad m) => (b -> a -> m b) -> b -> a -> m b foldlM _ acc [] = return acc
foldlM f acc (x:xs) = do
acc' <- f acc x
foldlM f acc' xs
例
code:hs
>> let f a e = do { print e ; return $ e : a }
0
1
2
3
以下2つは同じ
code:hs
code:hs
do
a2 <- f a1 x1
a3 <- f a2 x2
...
f am xm