At first glance I thought these two functions would work the same:
firstM _ [] = return Nothing
firstM p (x:xs) = p x >>= \r -> if r then return (Just x) else firstM p xs
firstM' p xs = fmap listToMaybe (mapM p xs)
But they don't. In particular, firstM
stops as soon as the first p x
is true. But firstM'
, because of mapM
, needs the evaluate the whole list.
Is there a "lazy mapM
" that enables the second definition, or at least one that doesn't require explicit recursion?