Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I implemented and and or:

-- or is like and, only it returns True if 
-- any of the boolean values in a list is True.
or' :: [Bool] -> Bool
or' []     = False
or' (x:xs) = x || or' xs 

--and takes a list of boolean values and returns True only if 
-- all the values in the list are True.
and' :: [Bool] -> Bool
and' [] = False
and' (x:xs) = x && and' xs

Is pattern matching the most elegant solution here?

Also, should or' [] and and' [] return False? It makes sense for them to do so when passing in a non-null input.

Example: or' [False, False]

But, how about the behavior of or' [] or and' []? Does False make sense here?

share|improve this question
add comment

3 Answers 3

up vote 6 down vote accepted

Your or' function is fine.

and' [] should return True — that's what the built-in and [] does. As it is, your and' function is broken, and always returns False:

*Main> and' [True]
False
share|improve this answer
add comment

Consider that Bool is an algebraic data structure like any other in Haskell. Pattern matching is the most elegant solution, but you can use even more of it to be even more elegant!

-- import Prelude hiding (or)

or :: [Bool] -> Bool
or []         = False
or (False:bs) = or bs
or (True :_ ) = True
share|improve this answer
    
I like that this solution works based on first principles, not even relying on || and &&. –  200_success May 1 at 10:28
add comment

Also, should or' [] and and' [] return False? It makes sense for them to do so when passing in a non-null input.

No, it makes sense only for or'. Apart from translating them to basic mathematic quantifiers "Is any of the items true?" (False for no items) and "Are all of the items true?" (True for no items), you can try to evaluate your function with an example one-item list and confirm whether it meets the expected results:

or' [False]       = False
False || or' []   = False
False || False    = True
--       ^^^^^

and' [True]       = True
True && and' []   = True
True &&  True     = True
--       ^^^^

Is pattern matching the most elegant solution here?

It's OK, but most recursive functions can be written more concisely (= elegant?) with folds:

or' = foldr (||) False
and' = foldr (&&) True
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.