[Haskell-cafe] Re: Tail Recursion within the IO Monad
Simon Marlow
simonmarhaskell at gmail.com
Fri May 18 07:20:18 EDT 2007
Stefan O'Rear wrote:
> 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
In a moment of insanity, I discounted reverse because I thought it had linear
stack usage, but of course it can be written (and is) to use only linear heap.
You're quite right, sorry for unnecessarily suggesting the use of
unsafePerformIO :-)
Simon
More information about the Haskell-Cafe
mailing list