与Haskell中的2个元素匹配的模式匹配列表 [英] Pattern match list with exactly 2 elements in Haskell

查看:393
本文介绍了与Haskell中的2个元素匹配的模式匹配列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Haskell,我试图用模式匹配来匹配一个只有2个元素的列表。作为一个练习,我试图编写一个函数,它返回列表中的最后一个元素。到目前为止,我发现这一点:

  myButLast :: [a]  - > a 
myButLast [] =错误不能从空列表中取出一个,而是最后一个!
myButLast [x] =错误只有一个元素,不能从列表中取出一个!
myButLast [x:y] = x
myButLast(x:xs)= myButLast xs

现在myButLast [x:y]这行显然是不正确的,但我不知道如何匹配恰好包含2个元素的列表,因为这是我在那里想要做的。我读过这个( http://learnyouahaskell.com/syntax-in-functions#pattern-matching )页面,它帮助了我很多,但我还没有完全在那里......

p> myButLast :: [a] - > a
myButLast [] =错误空列表
myButLast [x] =错误太少元素
myButLast [x,_] = x
myButLast(x:xs )= myButLast xs

这是 99个问题


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

解决方案

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.

这篇关于与Haskell中的2个元素匹配的模式匹配列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆