How to avoid stack space overflows?

后端 未结 3 1202
迷失自我
迷失自我 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 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.

提交回复
热议问题