title: Pattern match list with exactly 2 elements in Haskell
body: <p>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:</p>
  
  <pre><code>myButLast :: [a] -&gt; 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
  </code></pre>
  
  <p>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 (<a href="http://learnyouahaskell.com/syntax-in-functions#pattern-matching" rel="noreferrer">http://learnyouahaskell.com/syntax-in-functions#pattern-matching</a>) page and it helped me a lot, but I'm not completely there yet...</p>