6

以下程序破坏了堆栈:

__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)

失败

堆栈空间溢出:当前大小 8388608 字节。使用`+RTS -Ksize -RTS'来增加它。

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

4

1 回答 1

15

使用了尾调用优化,但(i+1)表达式会被重击,并且在最后评估它们会导致堆栈溢出。

于 2012-03-14T17:12:49.143 回答