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.
The custom of having an 'x' at the end of a message started as a way to symbolise a kiss. It was used between lovers. However, these days it is more often used as a way of implying you are being friendly, not formal. This is especially important now that so much communication is written, rather than spoken.
Kiss. The letter X is widely used at the end of text messages and emails to signify a "Kiss." It can be typed in either uppercase (X) or lowercase (x) without significantly altering its meaning.
“X”: This is a simple, respectful nod, indicating that everything is going absolutely fine. “XX”: This indicates strong professional hostility.
If you've been sent two Xs, then there's a fair chance the sender is being affectionate. (Generally, the number of Xs sent is proportional to the level of affection.) However, if you've been sent one X, be aware that one X is often used simply to add a warm tone to a message.
:
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 _
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With