findM :: Monad m => (a -> m Bool) -> m [a] -> Maybe (m a)
I cannot implement it by myself. I could use some pointers
find looks like:
find f as = listToMaybe $ filter f as
so I tried:
findM f as = filterM f as >>= listToMaybe
but it doesnt work.
No. It is not possible. However, you can write a function with the signature:
The reason it is not possible is because in order to figure out if the
Maybehas constructorJust xorNothing, you have to get the value out of the monad. Which means that theMaybemust be inside the monad at the end, since it is not possible in general to extract a value from inside a monad. (That is the whole point of monads, after all.)For example, given your signature to
findM, you could write some obviously incorrect functions:The function
extractBoolis obviously impossible, sofindMcannot have that signature.Here is an implementation of
findM:I am not sure of a simpler way to implement it — this seems fairly clean, and it works on infinite lists.
Changing the signature from using an
m [a]to using[a]makes it more useful and easier to use. You’ll quickly figure out why, if you implement both interfaces.