以下程序会破坏堆栈:
__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
,因此尾调用优化应该是可能的。
使用了尾调用优化,但是(i+1)
表达式会被重击,最后对它们求值会导致堆栈溢出。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)