Pattern matching on the last element of a List

  • A+

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 ?


If you have GHC 6.10 or newer, use a view pattern.

View patterns permit calling the view function inside the pattern and matching against the result:

size (view -> Unit) = 1 size (view -> Arrow t1 t2) = size t1 + size t2 

That is, we add a new form of pattern, written

expression -> pattern 

that means “apply the expression to whatever we're trying to match against, and then match the result of that application against the pattern.” The expression can be any Haskell expression of function type, and view patterns can be used wherever patterns are currently used.

Define head' as

{-# LANGUAGE ViewPatterns #-}  head' :: [a] -> a head' (last -> l) = l 

It works as you expect.

λ> head' [3,5,7] 7 λ> head' [] *** Exception: Prelude.last: empty list 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: