[Haskell-cafe] generating Maybe
Stuart Cook
scook0 at gmail.com
Wed Nov 7 18:06:22 EST 2007
On 11/8/07, Tim Newsham <newsham at lava.net> wrote:
> Data.Maybe has functions for processing Maybe's but nothing useful
> for creating maybe. I think the following would be a very useful
> addition, a guarded function:
>
> guarded :: (a -> Bool) -> (a -> b) -> a -> Maybe b
> guarded p f x | p x = Just (f x)
> | otherwise = Nothing
>
> such a function in the std libs would make functions like "unfoldr"
> more attractive -- uses of foldr nearly always encapsulate this
> notion.
How about this variant:
ensure :: (MonadPlus m) => (a -> Bool) -> a -> m a
ensure p x | p x = return x
| otherwise = mzero
Which as Jonathan points out, could also be written:
ensure p x = guard (p x) >> return x
Now we can define
guarded p f x = ensure p x >>> fmap f
Stuart
More information about the Haskell-Cafe
mailing list