Reputation: 135
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. I've tried doing this so far:
fold :: [Bool] -> Bool
fold xs = foldr (x==True) xs
where x:xs
Upvotes: 0
Views: 2899
Reputation: 4635
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. In particular, if you look at a call to foldr
:
foldr (\ x y -> ...) z xn
If xn
is empty, this will evaluate to 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:
foldr (\ x y -> x == True && ...) z xn
and y
means 'similarly for the rest of the elements', which you also want to be true:
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. If there are no elements by convention they are 'all' true, so you want True
for this case:
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:
foldr (\ x y -> x && y) True xn
But Haskell has a special notation for (\ x y -> x && y)
: (&&)
, specifically because this is a common case:
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 xn
Upvotes: 4
Reputation: 116139
You want and xs
to "and" a list of booleans. Equivalently, foldr (&&) True xs
or all id xs
also work.
Recall that foldr
takes a function (e.g. (&&)
) and a base case (e.g. True
). Your code lacks both.
Upvotes: 5