Many higher-order functions can be defined in term of the fold
function. For example, here is the relation between filter
and foldl
in Haskell.
myFilter p [] = []
myFilter p l = foldl (\y x -> if (p x) then (x:y) else y) [] (reverse l)
Is there a similar relation between their monadic versions filterM
and foldM
? How can I write filterM
in term of foldM
?
I tried hard to find a monadic equivalent to \y x -> if (p x) then (x:y) else y
to plug into foldM
without success.