library of monadic functions [was: Why no findM ? simple Cat revisited]

Jorge Adriano jadrian@mat.uc.pt
Wed, 20 Nov 2002 20:25:46 +0000


> I appreciate your comment.
> I agree that the type of findM should be the one you suggested,
> and it still fits my original purpose. It's no more than a step arout.
>
> \begin{code}
>
> import IO
> findM f [] =3D return Nothing
> findM f (x:xs) =3D do { b <- f x; if b then return (Just x) else findM =
f xs }
>
> isLeft (Left _) =3D True
> isLeft _ =3D False
>
> main =3D findM (>>=3Dreturn.isLeft) (hCat stdin)
> where hCat h =3D try (hGetLine h>>=3DputStrLn) : hCat h
>
> \end{code}

Yes, you are right.=20
It was enough because, you don't really care about what you found, you ju=
st=20
want to search and stop when you do find something. You are returning the=
=20
action that returned an element that satisfied your=20
condition, not the actual element like before.

> I expetct the next Haskell Library Report includes findM.
> It's obviously useful.

I think both versions can be very useful:
findM          :: (Monad m) =3D> (a -> m Bool) -> [a] -> m (Maybe a)
findM'          :: (Monad m) =3D> (a -> Bool) -> [m a] -> m (Maybe a)

Same can be said for,
takeWhileM :: (Monad m) =3D> (a -> m Bool) -> [a] -> m [a]
takeWhileM' :: (Monad m) =3D> (a -> Bool) -> [m a] -> m [a]

both would be usefull for different purposes.
Oh and since we're on it I also miss,
iterateM  :: (Monad m) =3D> (a -> m a) -> a -> m [a]
untilM :: (Monad m) =3D> (a -> m a) -> a -> m [a]
etc etc...

I've just been coding them as I need them, like many of you I suppose.
J.A.