Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on the last element of a List

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 ?

like image 487
Nicolas Henin Avatar asked Dec 07 '22 12:12

Nicolas Henin


1 Answers

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.

like image 179
chepner Avatar answered Jan 14 '23 14:01

chepner