untilM and scanM

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

untilM and scanM

Jan Snajder
Hi,

is there a reason why there is no monadic version of "until" in the
Haskell libraries? It would be defined as follows:

untilM :: (Monad m) => (a -> Bool) -> (a -> m a) -> a -> m a
untilM p f x | p x       = return x
             | otherwise = f x >>= untilM p f

The same applies to scanM, also not part of the libraries:

scanM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m [a]
scanM f q [] = return [q]
scanM f q (x:xs) =
   do q2 <- f q x
      qs <- scanM f q2 xs
      return (q:qs)

I often find myself in need for these. To me these seem idiomatic enough
to be included in the library. But since they is not, I guess there must
be another, more idiomatic way to do this.

Thank you,
Jan

Reply | Threaded
Open this post in threaded view
|

untilM and scanM

Brent Yorgey-2
On Mon, Jan 05, 2009 at 02:16:11PM +0100, Jan Snajder wrote:

> Hi,
>
> is there a reason why there is no monadic version of "until" in the
> Haskell libraries? It would be defined as follows:
>
> untilM :: (Monad m) => (a -> Bool) -> (a -> m a) -> a -> m a
> untilM p f x | p x       = return x
>              | otherwise = f x >>= untilM p f
>
> The same applies to scanM, also not part of the libraries:
>
> scanM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m [a]
> scanM f q [] = return [q]
> scanM f q (x:xs) =
>    do q2 <- f q x
>       qs <- scanM f q2 xs
>       return (q:qs)
>
> I often find myself in need for these. To me these seem idiomatic enough
> to be included in the library. But since they is not, I guess there must
> be another, more idiomatic way to do this.

There's no particular reason these aren't in the standard libraries
that I know of.  I've written untilM myself once or twice.  Perhaps
there are multiple slightly different ways to implement them and no
one can agree; or perhaps no one has ever proposed adding them.  But
there's no more idiomatic way to do this that I know of.

-Brent