Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

improve my Haskell code of all function

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
like image 447
user2730833 Avatar asked Jan 17 '26 21:01

user2730833


2 Answers

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.

like image 83
Simeon Visser Avatar answered Jan 19 '26 20:01

Simeon Visser


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
like image 30
Adam Wheeler Avatar answered Jan 19 '26 18:01

Adam Wheeler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!