简体   繁体   中英

What is the meaning of `sum [] = 0`?

sum :: [Int] -> Int
sum [] = 0
sum (x:xs) = x + sum xs

I do not understand what the purpose of the line sum [] = 0 is. I found this piece of code in a textbook (it did not go into detail as to what this line does.)

sum [] = 0 is the edge condition of the recursion.

Suppose we have sum [1, 4, 6, 8] . The list can be rewritten as 1:4:6:8:[] . The empty list is the last 'element'. The calculation is as follow (1 + ( 4 + (6 + ( 8 + 0)))) . When all the elements of the list have been traversed, what remains is the empty list. Adds zero to the calculated result and ends the iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM