Pattern match list with exactly 2 elements in Haskell
21,308
myButLast :: [a] -> a
myButLast [] = error "empty list"
myButLast [x] = error "too few elements"
myButLast [x, _] = x
myButLast (x: xs) = myButLast xs
This is the second quesion in 99 questions.
Author by
Admin
Updated on July 19, 2022Comments
-
Admin almost 2 years
I just started learning Haskell and I'm trying to use pattern matching to match a list that has exactly 2 elements. As an exercise, I'm trying to write a function which returns the one but last element from a list. So far I found this:
myButLast :: [a] -> a myButLast [] = error "Cannot take one but last from empty list!" myButLast [x] = error "Cannot take one but last from list with only one element!" myButLast [x:y] = x myButLast (x:xs) = myButLast xs
Now the line with myButLast [x:y] is clearly incorrect, but I don't know how to match a list that has exactly 2 elements, as that is what I'm trying to do there. I read this (http://learnyouahaskell.com/syntax-in-functions#pattern-matching) page and it helped me a lot, but I'm not completely there yet...