以下程序打击堆栈:
__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
评估的最后一件事,因此应该可以进行尾调用优化。
答案 0 :(得分:15)
使用了尾部调用优化,但(i+1)
表达式被thunked,并在最后评估它们导致堆栈溢出。