we use (x:xs)
to pattern match on the first element as in this example :
head' :: [a] -> a
head' xs = case xs of [] -> error "No head for empty lists!"
(x:_) -> x
is there a way to pattern match on the last element ?
No, because there is no constructor of type [a] -> a -> [a]
to match.
You can use []
and :
for pattern matching because they are, by definition, the building blocks of a list value. []
is the way to create an empty list. :
is the way to build a new list from an element and another list. Functions like append
do not create new lists by themselves; they return lists created by :
and/or []
.
The exception is if you happen to know the length of the list in advance, in which case you can match the last element by matching all of the elements explicitly.
lastOfFour :: [a] -> a
lastOfFour (_:_:_:x:[]) = x
lastOfFour (_:_:_:_:_) = error "Too many elements"
lastOfFour _ = error "Too few elements"
The first error message is triggered if you can match at least 4 elements, and the remaining list is not empty; the second by any list that isn't matched by one of the first two.
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