[英]relation between monadic filter and fold
可以根据fold
函数定义许多高阶函数。 例如,这里是Haskell中filter
和foldl
之间的关系。
myFilter p [] = []
myFilter p l = foldl (\y x -> if (p x) then (x:y) else y) [] (reverse l)
他们的filterM
版本filterM
和foldM
之间是否有类似的关系? 如何在filterM
中编写foldM
?
我努力找到一个等价于\\yx -> if (px) then (x:y) else y
插入foldM
但没有成功。
就像DM的答案一样,只有没有reverse
。 让类型指导您:
import Control.Monad
{-
foldM :: (Monad m) => (b -> a -> m b) -> b -> [a] -> m b
filterM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
-}
filtM :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
filtM p xs = foldM f id xs >>= (return . ($ []))
where
f acc x = do t <- p x
if t then return (acc.(x:)) else return acc
不确定它有任何意义(因为它有那种奇怪的reverse
),但至少它的类型检查得很好:
myFilterM :: Monad m => (a -> m Bool) -> [a] -> m [a]
myFilterM p l = foldM f [] (reverse l)
where
f y x = do
p1 <- p x
return $ if p1 then (x:y) else y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.