gpt4 book ai didi

haskell - 为什么这个 Haskell 程序中没有使用尾调用优化?

转载 作者:行者123 更新时间:2023-12-04 13:24:17 24 4
gpt4 key购买 nike

以下程序破坏了堆栈:

__find_first_occurrence :: (Eq b) => b -> [b] -> Int -> Int
__find_first_occurrence e [] i = -1
__find_first_occurrence e (x:xs) i
| e == x = i
| otherwise = __find_first_occurrence e xs (i + 1)

find_first_occurrence :: (Eq a) => a -> [a] -> Int
find_first_occurrence elem list =
__find_first_occurrence elem list 0

main = do
let n = 1000000
let idx = find_first_occurrence n [1..n]
putStrLn (show idx)

失败

Stack space overflow: current size 8388608 bytes. Use `+RTS -Ksize -RTS' to increase it.



但是,据我了解,可能递归调用 __find_first_occurrence__find_first_occurrence 评估的最后一件事,因此应该可以进行尾调用优化。

最佳答案

使用尾调用优化,但 (i+1)表达式被 thunked,最后对它们求值会导致堆栈溢出。

关于haskell - 为什么这个 Haskell 程序中没有使用尾调用优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9706589/

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