[Haskell-cafe] Re: How do I do conditional tail recursion in a monad?

apfelmus apfelmus at quantentunnel.de
Wed Mar 21 10:09:29 EDT 2007

DavidA wrote:
> I would like to write a function untilM, which would be to until as mapM is to 
> map.
> An example use would be if I had a function
> dice :: State Int Int
> which returns random dice throws within a state monad.
> Then I'd like to be able to do something like
> untilM (\(s,p)-> s>=100) f (0,1)
>     where f (s,p) = do d <- dice
>                        return (s+d, p*d)
> This should throw dice until the sum exceeds 100, and keeping track of the 
> product as we go along.

How about going with an infinite list of random numbers with no monads

  . dropUntil ((>= 100) . fst)
  . scanl' (\(s,p) d -> (d+s,p*d)) (0,1)
  . randomRs (1,6)

Of course, this has the drawback that you cannot take further random
numbers afterwards.


More information about the Haskell-Cafe mailing list