I am wondering if there is a standard function that iterates a function that returns a (Maybe value) over an initial value, collecting the values in a list, but ending the list when it gets to Nothing. This function can be implemented for example like so:
iterateMaybe f a = a : iterMaybe (f a) where
iterMaybe Nothing = []
iterMaybe (Just a) = a : iterMaybe (f a)
or slightly differently like so:
iterateMaybe' f Nothing = []
iterateMaybe' f (Just a) = a : iterateMaybe' f (f a)
None of the functions that Hoogle finds match.
It's a special case of unfoldr
.
iterateMaybe f = unfoldr (fmap (\s -> (s,s)) . f)
The difference is list returned by unfoldr
won't include the initial element.