[Haskell-cafe] Re: Tail Recursion within the IO Monad

Stefan O'Rear stefanor at cox.net
Thu May 17 09:33:00 EDT 2007


On Thu, May 17, 2007 at 11:22:34AM +0100, Simon Marlow wrote:
> sequence still isn't tail-recursive, although sequence_ is.  If you want a 
> tail-recursive sequence, the only way to do it is like this:
> 
> sequence' :: [IO a] -> IO [a]
> sequence' ms = do
>   let as = map unsafePerformIO ms
>   foldr seq (return ()) as
>   return as

sequence :: Monad m => [m a] -> m [a]
sequence ms = reverse `liftM` sequence' [] ms

sequence' l [] = return l
sequence' l (m:ms) = m >>= \x -> sequence' (x:l) ms

Stefan


More information about the Haskell-Cafe mailing list