gpt4 book ai didi

haskell - Haskell 尾递归如何工作?

转载 作者:行者123 更新时间:2023-12-03 06:10:42 24 4
gpt4 key购买 nike

我编写了这段代码,并且我假设 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com