Why is this recursive function optimized? (Haskell)

I wrote my own sum function in Haskell:

mySum [a] = a
mySum (a:as) = a + mySum as

And tested it with

main = putStrLn . show $ mySum [1 .. 400000000]

For error only.

Using the amount of Prelude in the same way:

main = putStrLn . show $ sum [1 .. 400000000]

I do not get stack overflow.

It can be a huge list, which I evaluate, especially if the list passed to my function is evaluated strictly, although my only reason not to suspect is that I am not getting errors using the Prelude sum with the same list.

+4
source share
3 answers

, , . , mySum . , , , mySum . , , , (+), mySum. , @DonStewart, , .

+4

, . "a" .

:

sum     l       = sum' l 0
   where
    sum' []     a = a
    sum' (x:xs) a = sum' xs (a+x)

{-# SPECIALISE sum     :: [Int] -> Int #-}
{-# SPECIALISE sum     :: [Integer] -> Integer #-}
{-# INLINABLE sum #-}

.

, , , "a" . :

    sum' []     !a = a
    sum' (x:xs) !a = sum' xs (a+x)

. , foldl' wrt. .

+10

: , , Haskell - ?

GHC , . , ", " . , , foldr foldl:

foldr (+) 0 (1:2:3:[])
1 + foldr (+) 0 (2:3:[])
1 + (2 + foldr (+) 0 (3:[]))
1 + (2 + (3 + foldr (+) 0 [])))
1 + (2 + (3 + 0))
1 + (2 + 3)
1 + 5
6

, foldr , , . , (+) , , . (+) , , .

, foldl - , ?

foldl (+) 0 (1:2:3:[])
foldl (+) (0+1) (2:3:[])
foldl (+) ((0+1)+2) (3:[])
foldl (+) (((0+1)+2)+3) []
((0+1)+2)+3
(1+2)+3
3+3
6

. -, foldl , , . (+) . , , " " GHC.

, , thunks, , foldl ( sum) Don), thunks (+)? foldl' :

foldl' (+) 0 (1:2:3:[])
foldl' (+) 1 (2:3:[])
foldl' (+) 3 (3:[])
foldl' (+) 6 []
6

, .

In conclusion, if your recursive calls remain the largest, most external (which corresponds to the position of the tail), they can be reduced with a lazy score. This is necessary but not sufficient to prevent the evaluation of your recursive function from using the O (n) stack and heap space. foldland foldrstyle recursion themselves take an O (n) stack and a bunch of space. foldl-line recursion with strict annotations on cumulative parameters is necessary for evaluating work in a constant space.

+3
source

Source: https://habr.com/ru/post/1542204/


All Articles