How does Haskell tail recursion work?

后端 未结 6 1968
傲寒
傲寒 2020-12-07 15:30

I wrote this snippet of code and I assume len is tail-recursive, but a stack overflow still occurs. What is wrong?

myLength :: [a] -> Integer         


        
6条回答
  •  天涯浪人
    2020-12-07 16:08

    The foldl carries the same problem; it builds a thunk. You can use foldl' from Data.List to avoid that problem:

    import Data.List
    myLength = foldl' (const.succ) 0
    

    The only difference between foldl and foldl' is the strict accumulation, so foldl' solves the problem in the same way as the seq and $! examples above. (const.succ) here works the same as (\a b -> a+1), though succ has a less restrictive type.

提交回复
热议问题