[Haskell-cafe] generating Maybe
Jonathan Cast
jonathanccast at fastmail.fm
Wed Nov 7 16:46:37 EST 2007
On 7 Nov 2007, at 12:40 PM, Tim Newsham 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.
guarded p f x = guard (p x) >> f x
which I would expect looks even better in practice:
[1..10] = unfoldr (\ n -> guard (n <= 10) >> return (n, n + 1)) 1
vs.
[1..10] = unfoldr (guarded (<= 10) (\ n -> return (n, n + 1)) 1
For example.
jcc
More information about the Haskell-Cafe
mailing list