head' :: [a] -> a
head' [] = error "No head for empty lists!"
head' (x:_) = x
head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists开发者_如何转开发!"
(x:_) -> x
I am asking for a fairly easy question which I don't understand.
In the code above, I see that it takes a list for an input.
But on the third line, it says (x:_)
which confuses me.
Can anyone explain to me why they wrote (x:_)
instead of [x:_]
?
And plus, I don't understand what (x:_)
means.
Thank you.
:
is a constructor for lists, which takes the head of the new list as its left argument and the tail as its right argument. If you use it as a pattern like here that means that the head of the list you match is given to the left pattern and the tail to the right.
So in this case the head of the list is stored in the variable x
and the tail is not used (_
means that you don't care about the value).
And yes, you can also use []
to pattern match against lists, but only lists of fixed size. For example the pattern [x]
matches a list with exactly one element, which is then stored in the variable x
. Likewise [x,y]
would match a list with two elements.
Your proposed pattern [x:y]
would thus match a list with one element, which matches the pattern x:y
. In other words, it would match a list of lists which contains exactly one list.
This is a concept called pattern matching. :
is an infix constructor, just like +
is an infix function. In Haskell you pattern match with constructors.
(1 : 2 : 3 : [])
Is the same as [1, 2, 3]
, the square bracket notation is just syntactic sugar for creating lists.
Your pattern (x : _)
means that you want to bind the first element of the list to x
and that you do not care about the rest of the list _
.
精彩评论