In the first chapter of the book, Programming in Haskell, it has the following function definition:
summ [] = 0
summ (n:ns) = n summ ns
What is the meaning of (n:ns)
, I guess from the function ns
is a list and n
is the first element of the original list, but what does the (n:ns)
notation actually tell Haskell? What part of the notation makes it clear what happens in the function?
CodePudding user response:
The sequence (n:ns)
is a shorthand for head - tail. Quite literally, the first value, the head, is called n
and the remained are the other, potentially plural, n
s, which is why it is called ns
.
Haskell has pattern matching. So, if I say (n:ns) = [1,2,3]
then Haskell will pattern match n
to 1
, and ns
to match [2,3]
. Effectively, n:ns
salami slices the first value off the front of the list.
The algorithm for calculating the sum of a list in Haskell is recursive. If the list is empty, [ ]
, then zero is returned. Otherwise, we slice off the first value from the list, n
, and add it to the result.
Haskell has a REPL, called ghci, and using this is fundamental to getting the hang of the language.