I am looking for a function that is basically similar to mapM in the list โ it performs a series of monadic actions that take each value in the list as a parameter โ and each monadic function returns m (Maybe b) . However, I want it to stop after the first parameter, which causes the function to return a Just value, and not execute more after that and return that value.
Well, it will probably be easier to just show a signature like:
findM :: (Monad m) => (a -> m (Maybe b)) -> [a] -> m (Maybe b)
where b is the first value of Just . Maybe the result is from find ing (in the case of an empty list, etc.) and has nothing to do with Maybe returned by the Monadic function.
I cannot implement this with the simple use of library functions. I could use
findM f xs = fmap (fmap fromJust . find isJust) $ mapM f xs
which will work, but I tested this, and it seems that all monadic actions are performed before the find call, so I can not rely on laziness here.
ghci> findM (\x -> print x >> return (Just x)) [1,2,3] 1 2 3 -- returning IO (Just 1)
What is the best way to implement this function that does not perform monadic actions after the first "simple" return? Something to do:
ghci> findM (\x -> print x >> return (Just x)) [1,2,3] 1 -- returning IO (Just 1)
or even, ideally,
ghci> findM (\x -> print x >> return (Just x)) [1..] 1 -- returning IO (Just 1)
I hope there is an answer that does not use explicit recursion and, if possible, is a composition of library functions? Or maybe even without dots ?