Reputation:
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...
Upvotes: 18
Views: 28634
Reputation: 1866
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.
Upvotes: 26