How to avoid stack space overflows?

后端 未结 3 1260
迷失自我
迷失自我 2021-02-06 14:20

I\'ve been a bit surprised by GHC throwing stack overflows if I\'d need to get value of large list containing memory intensive elements. I did expected GHC has TCO so I\'ll neve

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 14:54

    These links here will give you a good introduction to your problem of too many thunks (space leaks).

    If you know what to look out for (and have a decent model of lazy evaluation), then solving them is quite easy, for example:

    {-# LANGUAGE BangPatterns #-}                        
    
    import Data.List                                     
    
    fibs' = unfoldr (\(!a,!b) -> Just (a,(b,a+b))) (0,1) 
    
    main = do                                            
        print $ fibs' !! (10^6)  -- no more stack overflow                   
    

提交回复
热议问题