Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the implemention of sum function

Tags:

haskell

I started to play a bit with Haskell and came across the following implementation of the sum function:

sum [] = 0
sum (x:xs) = x + sum xs

And then there's an explanation that shows how the function would behave on a real example:

sum [1,2,3]

1 + (sum [2,3])
1 + (2 + sum [3])
1 + (2 + (3 + sum []))
1 + (2 + (3 + 0))
= 6

I don't understand, why every time sum [x] is called, the list gets smaller by 1 element?

My only assumption is that when the construction (x:xs) is executed, then the element x of the list, not only is retrieved, but also removed (similar to the stacks pop() method.), but I am not sure about this.

like image 268
VCODE Avatar asked Jun 01 '26 21:06

VCODE


1 Answers

In the notation x:xs, x is the head of the list, which is 1 item, and xs is the tail of the list, which is a list of 0 or more items.

Since the recursive call is on xs, the problem size set gets reduced by 1 with each level of recursion.

like image 163
wvdz Avatar answered Jun 04 '26 13:06

wvdz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!