How to avoid stack space overflows?

后端 未结 3 1201
迷失自我
迷失自我 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                   
    
    0 讨论(0)
  • 2021-02-06 15:02

    All of the definitions (except the useless fib_at) will delay all the + operations, which means that when you have selected the millionth element it is a thunk with a million delayed additions. You should try something stricter.

    0 讨论(0)
  • 2021-02-06 15:10

    As other have pointed out, Haskell being lazy you have to force evaluation of the thunks to avoid stack overflow. It appears to me that this version of fibs' should work up to 10^6:

    fibs' = unfoldr (\(a,b) -> Just (seq a (a, (b, a + b) )))  (0,1)
    

    I recommend to study this wiki page on Folds and have a look at the seq function.

    0 讨论(0)
提交回复
热议问题