Domanda

Il seguente programma soffia lo stack:

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

fallisce con

.

Stack Space Overflow: Dimensione corrente 8388608 Bytes.Usa `+ rts -ksize -Rts 'per aumentarlo.

Tuttavia, per quanto ne capisco, la possibile chiamata ricorsiva a __find_first_occurrence è l'ultima cosa valutata da __find_first_occurrence, quindi l'ottimizzazione della chiamata di coda dovrebbe essere possibile fare.

È stato utile?

Soluzione

Viene utilizzata l'ottimizzazione della cella della coda, ma le espressioni (i+1) vengono tessere e valutandole all'estremità provoca la pila di traboccare.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top