I am trying to implement all function in Haskell, it works fine but I think my base case is not good , if I set the result of the base case to False it makes more sense, I mean not of the members of an empty list passes the test condition in real word so answer should be false but on the other hand if I define it to false the whole function does not work properly .
all' test [] = True
all' test (x:xs)
| not (test x) = False
| otherwise = all' test xs
Consider this: for an empty list the predicate holds for all elements in the list.
Why? Because there are no elements that violate it.
Therefore the base case of the empty list is True.
all is intended to have the same meaning as the statement in formal logic, ∀xϵL: test(x) where L is the list that is the first argument. If you aren't familiar with formal logic, the important thing to understand is that this statement "returns" true even for an empty list. This is called vacuous truth (see http://en.wikipedia.org/wiki/Vacuously_true if you are curious).
The fact that returning true on an empty list makes all' easier to implement is a good example of why vacuous truth is a good idea, but if you want to implement it to return False for an empty list all you have to do is add one more case.
all' _ [] = False --here I have changed test to _ since we don't care what it is
all' test x:[] = test x --the new case
all' test (x:xs)
| not (test x) = False
| otherwise = all' test xs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With