简体   繁体   English

如何在Haskell中修复处理成对的布尔值的程序?

[英]How can I fix this program dealing with pairs of Booleans in Haskell?

For part of a homework assignment in a beginner Haskell course, I'm trying to write a program that will take a list of pairs of Bools, and returns a list of Bools coming from the pairs of bools with an "&&" between them. 对于初学者Haskell课程中的一项家庭作业,我正在尝试编写一个程序,该程序将获取一对布尔值,并返回来自一对布尔值的布尔值列表,它们之间有一个“ &&”。 For example... 例如...

andandbool [(True,True),(True,False),(False,True),(False,False)] 

would return: 会返回:

[True, False, False, False]

I keep running into trouble, however. 但是,我一直遇到麻烦。 My code looks like this. 我的代码如下所示。

andandbool :: [(Bool,Bool)] -> [Bool]
andandbool [a] = [fst x && snd x | x <- [a]]

It works fine when I provide a list of only one pair, but reports "Non-exhaustive patterns in function andandbool" when I enter a list of multiple pairs. 当我仅提供一对对的列表时,它工作正常,但是当我输入多个对的列表时,报告“功能andandool中的非穷尽模式”。 Is there some sort of list comprehension that I'm missing? 我缺少某种列表理解吗? Any pointers in the right direction would be greatly appreciated. 朝正确方向的任何指针将不胜感激。

Now that I'm at my computer I'll turn my comment into an answer. 现在我在电脑上,我将把我的评论变成答案。

When you name the argument of the function [a] , Haskell interprets that as your function pattern matching on a list of one element. 当您命名函数[a]的参数时,Haskell会将其解释为与一个元素列表匹配的函数模式。 That's why your function only worked on one-element lists. 这就是为什么您的函数仅适用于一个元素列表的原因。 To fix it, just rename the function argument to something without brackets in the name: 要解决此问题,只需将function参数重命名为名称中没有方括号的内容:

andandbool :: [(Bool,Bool)] -> [Bool]
andandbool as = [fst x && snd x | x <- as]

That as argument will now match any list. as参数现在将匹配任何列表。

Edit: Like @Ankur mentioned, you can simplify this as: 编辑:就像@Ankur提到的那样,您可以将其简化为:

andandbool as = [x && y | (x, y) <- as]

If you really want to play code golf you can simplify this even more as: 如果您真的想打代码高尔夫,可以将其简化为:

andandbool = map (uncurry (&&))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM