[erlang-questions] lists:all/2 unexpected result for the empty list
Richard O'Keefe
ok@REDACTED
Wed Jul 20 04:56:56 CEST 2011
On 20/07/2011, at 1:09 PM, Michael Truog wrote:
> The choice of true for lists:all/2 with an empty list still seems arbitrary to me.
It is anything but!
Let's switch to Haskell for a minute.
foldr f e [] = e
foldr f e (x:xs) = f x (foldr f e xs)
That is, foldr f e [x1,x2,...,xn] = f x1 (f x2 ... (f xn e) ...)
Note that for uniformity, foldr f e [x] has to be f x e.
and = foldr (&&) True
or = foldr (||) False
"and" tests whether all the elements of a list are true
"or" tests whether at least one element of a list is true
Note that *no* value other than True could be used for "and";
*no* value other than False could be used for "or". Try the
opposite truth value and it just plain won't work.
map f [] = []
map f (x:xs) = f x : map f xs
all p = and . map p
any p = or . map p
That is, apply a predicate p to all the elements of a list,
and then check whether all (or any) of the results are true.
Expand out these definitions and you get
all p [] = True
all p (x:xs) = p x && all p xs
any p [] = False
any p (x:xs) = p x || any p xs
Once again, plugging anything other than True into the base
case of "all" could not possibly work.
aristotelian_all p [] = False
aristotelian_all p (x:xs) = all p (x:xs)
or
aristotelian_all p xs = not (null xs) && all p xs
and however you slice it, the unmotivated requirement to
return False for any empty list just makes the code
longer and less comprehensible. You should see what
horrors it inflicts on the code that USES it!
> However, I don't think there is a good argument for the choice being wrong.
You would have to convince every mathematician and logician on the
planet that they were doing quantifiers wrong.
The documentation probably didn't say anything about the issue
because it doesn't make any more sense for all(P, []) to return
false than for sum([]) to return -792.
More information about the erlang-questions
mailing list