Pattern match list with exactly 2 elements in Haskell

廉价感情. 提交于 2019-12-22 02:20:56

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/35378922/pattern-match-list-with-exactly-2-elements-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!