Reputation: 11
I am going through the school of haskell basics and on the functions on lists section it uses this expression to get the length of the list
intListLength (_:xs) = 1 + intListLength xs
I have tried manipulating this with different values where the one is and it seems to be multiplying even though the expression is with addition although the function is returning the correct value for the length of the list.
I was hoping someone would be able to explain what's happening here.
Upvotes: 1
Views: 1634
Reputation: 11743
intListLength :: [Integer] -> Integer
intListLength [] = 0
intListLength (x:xs) = 1 + intListLength xs
As the document you linked explains:
The first clause says that the length of an empty list is 0. The second clause says that if the input list looks like (x:xs), that is, a first element xconsed onto a remaining list xs, then the length is one more than the length of xs.
Since we don’t use x at all we could also replace it by an underscore: intListLength (_:xs) = 1 + intListLength xs.
The function intListLength
is adding 1
to a running sum for every element in the list. Every time intListLength
is called, an element is popped off the list, and a 1
is added to a running total created by the recursive call on the remaining elements of the list. When there are no more elements in the list, the empty list function head is matched and a 0
is added to the total. At that point, the total is returned.
Upvotes: 3
Reputation: 10814
intListLength (_:xs) = 1 + intListLength xs
In plain English this means "the length of a list starting with any element (_
) followed by the elements xs
is 1
plus then length of the list xs
".
Upvotes: 1