简体   繁体   English

如果值是true,则haskell中列表上的fold函数返回true

[英]fold function on a list in haskell returning true if values are true

Im trying to get a function with foldr to work on a list which has values such as 3>4,... etc and return True if the values in the list are true. 我试图获得一个具有foldr的函数以在具有诸如3> 4,...等值的列表上工作,如果列表中的值为true,则返回True。 I've tried doing this so far: 到目前为止,我已经尝试过这样做:

fold :: [Bool] -> Bool
fold xs = foldr (x==True) xs
        where x:xs

You want and xs to "and" a list of booleans. 您希望and xs “和”一个布尔列表。 Equivalently, foldr (&&) True xs or all id xs also work. 同样, foldr (&&) True xsall id xs也可以使用。

Recall that foldr takes a function (eg (&&) ) and a base case (eg True ). 回想一下, foldr具有一个函数 (例如(&&) )和一个基本情况 (例如True )。 Your code lacks both. 您的代码缺少两者。

Haskell gives you an incredible amount of control over what happens in your program, but you have to explicitly say everything you want to happen. Haskell为您提供了对程序中发生的事情的难以置信的控制,但是您必须明确地说出想要发生的一切。 In particular, if you look at a call to foldr : 特别是,如果您查看对foldr的调用:

foldr (\ x y -> ...) z xn

If xn is empty, this will evaluate to z . 如果xn为空,则将得出z Otherwise, the value will be the body of the function (the value of the ... ), whatever that is. 否则,该值将是函数体(值了... ),不管它是什么。 You want the function to be true only under certain conditions, so you probably want that expression to be an application of the && operator: 您希望函数仅在特定条件下才为真,因此您可能希望该表达式成为&&运算符的应用程序:

foldr (\ x y -> ... && ...) z xn

x is the value of the first element, which you want to be true: x是第一个元素的值,您要设为true:

foldr (\ x y -> x == True && ...) z xn

and y means 'similarly for the rest of the elements', which you also want to be true: y意思是“对于其余元素类似”,您也希望是真的:

foldr (\ x y -> x == True && y) z xn

You need to pass in for z what you want the value to be when there are no elements. 当没有元素时,您需要为z传递想要的值。 If there are no elements by convention they are 'all' true, so you want True for this case: 如果没有约定,则所有元素均为“ true”,因此在这种情况下您希望为True

foldr (\ x y -> x == True && y) True xn

Now, if x is a boolean already, x == True is just the same as x , so we can simplify that expression: 现在,如果x已经是布尔值,则x == Truex相同,因此我们可以简化该表达式:

foldr (\ x y -> x && y) True xn

But Haskell has a special notation for (\\ xy -> x && y) : (&&) , specifically because this is a common case: 但是Haskell对于(\\ xy -> x && y)(&&)有特殊的表示法,特别是因为这是一种常见情况:

foldr (&&) True xn

And, because this function is a common need, there's a function for it already in the standard library, called and : 而且,由于该功能是一种常见的需要,有标准库的一个功能,它已经被称为and

and xn

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

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