Question

I'm trying to write a function that will work as follows;

conjunction [a, b, c] == And a (And b c)

I'm unsure where exactly the best way to do this, I assume list recursion using the x:xs pattern?

Was it helpful?

Solution 2

Here is some working code, based on J. Abrahamson's comment-

data MyBool = MyTrue | MyFalse | And MyBool MyBool deriving (Show)



main = do
    print $ foldr1 And [MyTrue, MyFalse, MyTrue, MyTrue, MyFalse, MyTrue]

(I assumed your uppercase "And" was a constructor and not a typo....)

This doesn't cover the case for [], which you could pull out using pattern matching.

OTHER TIPS

Here's one option. If there are no elements in the list, then their conjunction is True by convention. So you have

conjunction []     = True

If there is more than one element, the conjunction is True if that element is True, and the conjunction of all the other elements are True

conjunction (x:xs) = x && conjunction xs

This particular pattern (iterating through a list one element at a time, and combining with a binary function) is very common in function programming. In fact, it's so common that there is a helper function for it, called foldr. So you could write

conjunction xs = foldr (&&) True xs

where the first argument specifies the combining function, and the second argument specifies the value when the list is empty.

Or you could just use an already defined function, like

conjunction = and
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top