sequence causing stack overflow on pretty small lists

John Alfred Nathanael Chee cheecheeo at
Wed Aug 28 04:19:13 CEST 2013

This is somewhat related:

This also solves the concrete problem you gave in your original post
(in reverse order):

import Control.Monad
import System.Random

sequencel :: Monad m => [m a] -> m [a]
sequencel = foldM (\tail m -> (\x -> return $ x : tail) =<< m) []

main :: IO ()
main = print =<< sequencel (replicate 1000000 (randomIO :: IO Integer))

Following on Reid's point, maybe it's worth noting in the
documentation that replicateM, mapM, and sequence are not tail
recursive for Monads that define (>>=) as strict in the first

On Tue, Aug 27, 2013 at 6:07 AM, Niklas Hambüchen <mail at> wrote:
> On 27/08/13 20:37, Patrick Palka wrote:
>> You can use ContT to force the function to use heap instead of stack
>> space, e.g. runContT (replicateM 1000000 (lift randomIO)) return
> That is interesting, and works.
> Unfortunately its pure existence will not fix sequence, mapM etc. in base.
> _______________________________________________
> Libraries mailing list
> Libraries at

Love in Jesus Christ, John Alfred Nathanael Chee

More information about the Libraries mailing list