[Haskell-cafe] Re: golf, predicate check function for MonadPlus

Jon Fairbairn jon.fairbairn at cl.cam.ac.uk
Tue Jul 7 05:10:03 EDT 2009


Dan Doel <dan.doel at gmail.com> writes:

> On Thursday 02 July 2009 6:36:09 am Jon Fairbairn wrote:
>> check :: (MonadPlus m) => (a -> Bool) -> a -> m a
>> check p a
>>     | p a = return a
>>     | otherwise = mzero
>
> 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)

Yes, I've had occasion to use something like that too,
eg things similar to:

reverse . unfoldr (stopAt (==0) (swap  . flip divMod 10))
   where swap (a,b) = (b,a)

> And of course: check = flip stopAt id . not

or, equally, "stopAt p f = fmap f . check (not . p)"

Granted,

reverse . unfoldr (fmap (swap . flip divMod 10) . check (/=0))

isn't /quite/ as nice as the first version, but I imagine one could get
used to it.

-- 
Jón Fairbairn                                 Jon.Fairbairn at cl.cam.ac.uk




More information about the Haskell-Cafe mailing list