Reputation: 339
I'm currently learning haskell then I came to this exercise where I have to define a function that gets the product of a list of numbers. I was provided with choices and since I am new to haskell there are some notations that I am a bit unclear of.
So I saw this definition on one of the choices:
p [x, xs] = x * product xs
I can understand this quite a bit, it means to get the product of the list and then multiply it with the value of x.
Then I saw this other definition on one of the other choice:
p (x : xs) = x * product xs
Which I totally do not understand. It uses parenthesis and a colon which I am having a hard time looking for their definition. I appreciate if someone could enlighten me with regards the syntax and semantics.
Upvotes: 1
Views: 1178
Reputation: 370397
[x, xs]
is a list containing two elements. The first element is called x
and the second is called xs
. So in this case product xs
does not calculate the product of the list, it calculates the product of the second element. Since the elements of the list can't be lists themselves (or else multiplying with x wouldn't work), this is a type error.
x : xs
is a list that contains at least one element. Its first element is called x
and the list containing its remaining elements is called xs
.
Upvotes: 5
Reputation: 39916
:
is the cons operator, which appends an element to a list
(x : xs)
is pattern-matching a list into an element x
and the rest of the list xs
let's get a concrete example:
l = [1,2,3]
show_rest_of_list (x:xs) = xs
show_rest_of_list l
-- would return [2,3]
play_with_list (x:xs) = x : x : xs
play_with_list l
-- would return [1,1,2,3]
Upvotes: 4