我写了这段代码,我假设 len
是尾递归的,但仍然会发生堆栈溢出。怎么了?
myLength :: [a] -> Integer
myLength xs = len xs 0
where len [] l = l
len (x:xs) l = len xs (l+1)
main = print $ myLength [1..10000000]
最佳答案
请记住,Haskell 是懒惰的。除非绝对必要,否则您的计算 (l+1) 不会发生。
“简单”的解决方法是使用“$!”强制评估:
myLength :: [a] -> Integer
myLength xs = len xs 0
where len [] l = l
len (x:xs) l = len xs $! (l+1)
main = print $ myLength [1..10000000]
关于haskell - Haskell 尾递归如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/412919/