[Haskell-cafe] golf, predicate check function for MonadPlus (was
Re: How to read safely?)
Antoine Latter
aslatter at gmail.com
Tue Jul 7 01:58:08 EDT 2009
On Mon, Jul 6, 2009 at 8:49 PM, Dan Doel<dan.doel at gmail.com> wrote:
>
> I've often noticed the need for a similar function in conjunction with
> unfoldr:
>
> -- This is overly general for unfoldr, but it lines up with check
> stopAt :: (MonadPlus m) => (a -> Bool) -> (a -> b) -> a -> m b
> stopAt p f x
> | p x = mzero
> | otherwise = return (f x)
>
> -- stopAt p f x = guard (not $ p x) >> return (f x)
> -- stopAt p f = liftM2 (>>) (guard . not . p) (return . f)
> -- etc.
>
> Then you can write:
>
> unfoldr (stopAt p $ f)
>
I have the following function sitting around:
unfoldUntil :: (b -> Bool) -> (b -> (a, b)) -> b -> [a]
unfoldUntil p f n = unfoldr g n
where g m | p m = Nothing
| otherwise = Just $ f m
But I don't remeber where I picked it up from. It looks like it fills
a similar niche.
Antoine
More information about the Haskell-Cafe
mailing list