189 points · by earthboundkid · 6y ago · 210 comments
sum([1,1]) = 1 + 1 = 2
sum([1]) = 1
sum([]) = 0
0 + n = n + 0 = n
Zero is the unit with respect to addition, so when we add together a list of no numbers, we ought to get back zero.you can `from math import prod` in python3.8
prod([2,2]) = 2*2 = 2
prod([2]) = 2
prod([]) = 1
1 * n = n * 1 = n
The same way, one is the unit with respect to multiplication. So, multiplying no numbers together gets you one. all([True,True]) = True && True = True
all([True]) = True
all([]) = True
True && x = x && True = x
You get the idea.That said, I do think there is something to the perspective presented in the article. Something which is not accidental to the algebraization of logic...
According to the Curry-Howard correspondence and the BHK interpretation of logic, there is a syntactic correspondence between types and logical formulas and between terms and proofs.
Here, the unit type corresponds with truth because it is trivially inhabited with a single inhabitant. The product type A * B is interpreted as logical conjunction because you need a proof of A and a proof of B to inhabit it.
The unit type (true) is the identity of the product type (and). Unit * A = A * Unit = A from an isomorphism perspective. From the category theory point of view, a Cartesian monoidal category is a monoidal category where the tensor product is the categorical product and the unit object is the terminal object. It's no coincidence that the terminal object is written as 1.
So, an n-ary sequence of propositions connected by ANDs is like an n-ary tuple type, and an empty sequence of propositions connected by ANDs is like the nullary tuple type, or in other words the trivially inhabited unit type.
ɪ, don't know.
The correct term is an identity.
We want this general property to hold:
sum([ sum(x[0:n]), sum(x[n:]) ]) == sum(x)
define sum([]) (n = 0) so that it holds
It works the same for prod, all, and any, and gives a hint as to what the answer should be if there were things like union(sets) (the empty set) or intersection(sets) (the universe, or union of all sets)
prod([2,2]) = 2*2 = 4
Right?Edit: could have picked better examples too imo... Id have used 1 + 0 = 1 and 2 × 1 = 2... basically you add 1s for free when multiplying, 0s for free when adding, and trues for free when "Alling".
An identity is something that does not change the left operand
a * i = a
0 for + and 1 for x pass this test.
But for Boolean && neither True nor False pass the identity test because,
( True as identity) False && True = False True && True = True
( False as identity)
False && False False True && False = False
Perhaps there is more to it....
a && True = a
a * i = a
the operation (denoted * above) is &&, and the identity (denoted i above) is True. Lets see how it holds out for all possible values of a: a && True =?= a
let a := True
True && True =?= True
correct!
a && True =?= a
let a := False
False && True =?= False
correct! if(all(requirements)) { proceed; }
If there are no requirements that need to be satisfied, then you should be able to proceed.Yes, precisely the point of the article. We mostly find it natural to think like moderns today, but civilization went along for thousands of years thinking differently.
def all(iterable):
for element in iterable:
if not element:
return False
return True
https://github.com/python/cpython/blob/master/Python/bltinmo...My favourite explanation comes from property based testing.
In general, you have the following property: For any lists xs and ys,
all(xs) and all(ys) == all(xs + ys)
If you want to keep that property as simple as possible, you have to define all([]) == True
If you want to go with the opposite, your property becomes more complicated.Mathematical definitions are somewhat arbitrary. It's up to us to choose definitions that make sense in our contexts. A general desire to make the resulting systems simple and uniform worked out well for many, many context.
Slight detour: that's also why defining 2 - 5 to have an answer is a good idea! Negative numbers were seen as a bit suspect, but they behave perfectly sensible. Same for complex numbers.
But: still we generally leave 0 / 0 undefined, because no answer would lead to a satisfying system.
But whenever I've tried to explain things like this to people, I've found so many just don't seem to see the issue, or to remotely care if they do. Their intuitive responses tend to be:
- It's an obscure issue, it's never gonna come up.
- Oh, well I mean it's obviously your fault for calling it that way with that implicit assumption. Why would you think that?
- Well it's the caller's responsibility to read the documentation/look at the source/test the code before they use this function, not my problem to try to fit it into every mathematically possible use case.
I feel like the notion of putting some more thought into what seems like an elementary API so that these issues don't come up and trip up users in the first place seems like a completely unjustifiable academic effort to them, if not an outright foreign one. Have you found any effective way to try to communicate stuff like this and hopefully actually convince people?
You can make 1/0 return infinity, and preserve some properties of fields. Though that works best, if your zeroes are also signed.
But for 0/0, I don't see nearly as many properties you can rescue.
all(xs) and all(ys) == all(xs + ys)
If I understand you correctly, the "and" should be an "implies" instead: all(xs) => (all(ys) == all(xs + ys))
Otherwise this law cannot be true since there exist xs for which !all(xs). (all(xs) and all(ys)) == all(xs + ys)
This is why you should always use parentheses unless it's absolutely obvious! I certainly had to check the docs to find out which way round it goes. I guess normally you're not dealing with Boolean variables so having == bind tighter makes more sense: y is not None and x == 7That wasn't necessarily a choice, it may have just been an oversight not to deal with the "empty list" case.
The fact that this blog post exists is a testament to this behavior being surprising.
I don't think any of the arguments - philosophical or otherwise - are very good from a practical standpoint, that is: is this behavior is not more likely to cause harm?
My gut feeling says that this behavior is somewhat unsafe, but then again Python is probably not the language to use when safety is a big concern.
A hypothetical safer language might be better off to define "all/any" only for non-empty list.
> That wasn't necessarily a choice, it may have just been an oversight not to deal with the "empty list" case.
If your general code gives you a answer for a corner case, it's a good hint that this might be a reasonable answer. Not a guarantee, though.
It includes a test for the empty case: `self.assertEqual(all([]), True)`. They knew what they were doing.
When observed planetary motions were found to be incompatible with the assumption, epicycles were introduced to keep the initial assumption working.
Are you my Intro to Operating Systems professor? Because he would take points away from answers on the exams for being more long-winded than necessary, even if the answer was correct.
Joking aside, your perspective is bizarre to me. You haven't offered any reasons to propose that all([]) should be False, but reject the given answers for it being True simply on the basis that the explanations are long-winded?
`all(x) == not any([not v for v in x])`
so `all([]) == not any([])` -> `True`
Also, I don't see why `any([]) == False` would be any more obvious than `all([]) == True`?
I've seen not-so-carefully designed APIs that violate your 'obvious' logic for 'any':
We had a system that you could send a list of topics, and it would return you all the datasets associated with those topics. The designer of the system decided that an empty list of topics would return all datasets, instead of nothing.
I suspect their reasoning was that giving people an option to get all datasets was useful, and that predictably returning nothing was useless.
But what they should have done in this situation for a clean API was to take an optional list of topics.
any([x, y]) == x or any([y]) == x or y or any([])
all([x, y]) == x and all([y]) == x and y and all([])
then any([]) must be false (otherwise x and y would never matter), and all([]) must be true.In the query API you're describing, does {topic1, topic2} find datasets on (topic1 OR topic2), or is it (topic1 AND topic2)? That's what determines whether more topics means more or fewer results, and whether {} should correctly find nothing or everything.
Yes, I know. My problem is with:
> Another reason we must have `all([]) == True`, because `any([])` should obviously be `False`.
Argument is of the form 'A, because B'. But I don't see how B is any more obvious than A here. They seem about equally obvious.
I can’t actually think of a coherent argument for returning anything besides true.
"This is a confusing situation, and no boolean answer we could give would satisfy the principle of least surprise, so we should throw an error."
I don't think there's a good argument to be made for returning False.
As an aside: I don't think there's anything particularly related to 'functional programming' about the arguments used here. But, yet, experience with functional programming tends to make people more careful about finding general principles that give you answers for corner cases like this, too.
The imperative code used in the Python standard library is just as compelling an argument for the Right Answer also being the simplest as any based in FP:
def all(iterable):
for element in iterable:
if not element:
return False
return True
In general, when I'm reviewing imperative code, I'm encouraging the authors to find ways to handle corner cases like empty lists organically within their code instead of with a special case check at the top. The organic handling seems to have a higher chance of producing the Right Answer.Common folk tend to disagree about whether zero is an even number. Calculating 0 mod 2 is a confusing situation, and no numeric answer we could give would satisfy the principle of least surprise, so we should throw an error.
I think True follows the principle of least surprise.
> I don't think there's anything particularly related to 'functional programming' about the arguments used here
It imparts a better understanding of algebraic abstractions, including what it means to recursively reduce a data structure.
I'm not sure how that python code is supposed to be especially simple or elucidating. I think the following Haskell code is reasonably elucidating, since it elides any need to manually define a special case or base case:
all = getAll . foldMap All
Where "All" is the conjunction ("and") monoid, as defined in Data.Monoid.Me too. I was just quoting the best argument (I found so far) for a different position.
> I'm not sure how that python code is supposed to be especially simple or elucidating. I think the following Haskell code is reasonably elucidating, since it elides any need to manually define a special case or base case:
The Python code wasn't for comparison to any Haskell implementation. If you can read Haskell, you'll likely prefer the Haskell version. But that's not the point.
The point is that amongst all imperative attempts, the most straightforward ones also naturally suggest what to do about the empty list.
Btw, in Haskell notation most normal people's mental model of how 'all' works is probably closer to:
all = foldl1 (&&)
Most normal people don't think about neutral elements of operations, and that they suggest a natural answer for folds over empty collections.Who are "most of us"? People on HN? People who do programming?
I've a professional programmer, but horrible at math. Don't have any formal education and even less education about discrete math. So for me this was educational and I thank the author for putting it down in writing and sharing the knowledge.
I'm sure I'm not alone on HN or in the software industry with this.
I'm also sure I'm sitting on bunch of knowledge you have no idea about, but when others share that, I don't shoot them down for it, I'm happy we're all helping each other understand things.
I, for one, also like the comments here as they expand and dive into more topics that again, "some of us" have not read/heard about before so grateful for that.
Lewis Carroll didn't know this, and treated universally quantified statements over an empty domain as false. Of course that's wrong; but I think it's over-specialising to claim that this is something obvious, or that everyone knows.
(Also, as others have said, if someone learns from this, then that's great! That's a positive impact, whereas saying "you should have known it already" is purely negative, so why bother?)
I do think most programmers would benefit a lot from learning the fundamentals of logic, or at the very least boolean algebra. after seeing some of the tortured expressions they write, I certainly wish my coworkers were more familiar with boolean simplification rules and identities.
I've lost count of the amount of times I've factored out the "not" from horrid expressions in my colleagues' code like "not this and not that" using Dr Morgan's law. Funny thing is I learnt Dr Morgan's in electronics a long time before I got to computers.
I think the problem is it's "boring" and people get hooked on doing stuff with programming. I can't blame them. But I wish more people remembered the fundamentals.
Would they, for example, have considered the statement "all unicorns have a horn" to be false?
In fact, the post mentions the statement "all stonemen are made of stone" which is assumed to be true under the greek logic, but according to the explanation should be false because there are no stonemen.
Your example ""all stonemen are made of stone" would be true under both modern and supposed Greek interpretations.
>>> min(['a', 'b'])
'a'
>>> min(['a'])
'a'
>>> min([])
float('-inf') # ???
An empty list is not a list of numbers. It's not a list of anything.(You can use typing hinting to indicate the type of an empty list, but type hints are ignored by the interpreter.)
You could invent a monoid instance of `float` for `<` which includes `inf` as an empty element and, if you ignore NaN, it kinda sorta works in isolation. However, adding infinity breaks a lot of other nice properties to the numbering system.
For example, the following identity of `min` is valid in the finite numbers.
``` n < min A ⟺ (∀ a ∈ A) n < a ```
The right part of the equation is always true if `A = ∅`, and according to our new monoid the left part is true if and only if `n ≠ ∞`.
To get what you want, use min(lst, default=-math.inf) .
In Python 2, you had
float('-inf') < ""
So you could sort of get away with that. But that positive infinity wasn't bigger than any string. And in Python 3 comparing strings and numbers just results in an error.Excellent point, thanks!
(infinity + 1) > infinity
which it isn't. I know about IEEE infs and nans, and neither are numbers, just useful conventions.
One could conclude that the definition of -> is not very logical but if one is to attach a formal meaning to -> it would seem hard to avoid this. One would need conditions like that when P -> Q we have to have that P and Q are related in some way but that does not sound like something that is very easy to formalize.
It also does not matter whether one uses intuitionistic logic. P /\ ~ P -> Q still holds.
In type theory False is the empty type and proving something about it can be done with case analysis. Since it is the empty type there are zero cases and one is immediately done and can prove anything.
Other similar definitions are that min of an empty set is infinity and max of an empty set is minus infinity. Min is monotone decreasing over set inclusion hence min of empty set must be the maximum possible value. Max is montone increasing in ser inclusion hence max of empty set must be the smallest possible value.
> (and)
#t
> (or)
#f
> (+)
0
And most surprising (although it's very convenient on second thought): > (* )
1
Thus multiplication on empty list gives 1.1 * x = x
0 + x = x
Lispers know this implicitly. You know they say learning Lisp makes you a better programmer? This is an example of that. Raymond Hettinger and many of the Python authors are Lispers are heart and this is obvious to them.
As a theoretical matter, "all unicorns are blue" is like a transfer function for a controller that can move an elevator from the bottom of the Empire State Building to the top in 0.01 seconds. Connecting words is like solving a math problem.
Trying to locate that unicorn, or bringing that controller out of state space and into reality, one quickly realizes the non-existence of unicorns and that the energy applied to that elevator in order to meet the time requirement would vaporize the equipment.
Requirements and metadata need not meet the realities that apply to data.
Hard reality does not always agree.
Nor do HN moderators, apparently.
But when you are building arbitrary systems, some design choices give you simpler and more applicable systems than others.
Why Swift specifically? This would be in the calling signature, implying there are inputs you can give said method that are nonsensical.
Your client code has to work with the behaviour of your function.
If you have a perfectly sensible answer for a corner case, just give that answer. Otherwise, you are forcing unnecessary extra case handling on your client code.
And that principle also tells you which answer your code should be giving: whatever makes the client code simpler.
Another example, perhaps more inspired from C conventions:
Imagine you have some functions that take a timeout as an argument. After the time is up, they should fail, if they haven't produced an answer yet.
Now, in these kinds of situations you often find that people choose 0 to mean an infinite timeout.
That's a bad idea, because it violates simple invariants like: if you run two statements with timeouts of t0 and t1, after at most t0 + t1 seconds, you should either have an answer or get an error.
(You can of course complicate the invariant by adding special cases for t0 or t1 being zero. But who likes special cases?)
Over the past few decades I’ve seen ten of thousands of non-blue things, and none of them were unicorns!
If more people understood them, there's a number of dumb internet debates that could finally die, where X -> Y isn't immediately obviously wrong to our human brains and may even sound correct but !Y -> !X is immediately obviously wrong.
Indeed they aren't! All unicorns are not blue.
The surprising thing is that all unicorns are red, too.
all(x + [True]) == all(x)
any(x + [False]) == any(x)
all(x + y) == (all(x) and all(y))
any(x + y) == (any(x) or any(y))
not all(x) == any(not xi for xi in x)
not any(x) == all(not xi for xi in x)
Any other values for all([]) and any([]) would cause some or all of these theorems to be correct for all values of x and y except the empty list. In practice this would mean you would have a bug in your program on most occasions where the argument of one of these functions was empty, unless you included a special case for empty sequences.For example, suppose you're processing a request that includes some tasks and some attachments. You might write something like this:
if any(task.is_failed() for task in request.tasks):
raise TaskFailed(request)
if any(x.is_too_large() for x in request.attachments):
raise AttachmentTooLarge(request)
Clearly for this code to do the right thing in the case where a request has tasks or attachments but not both, we need any([]) to be false. And the corresponding requirement applies to all([]) if our task interface is a little different: if not all(task.is_succeeded() for task in request.tasks):
raise TaskFailed(request)
Now, there are occasionally programs where you do need a special case for empty sequences; for example, if you have three search results, you might want to return a page containing just those results, but if you have zero, you probably don't want to just return an empty page — the user might think the software is just broken. And in the above example, if there are neither any tasks nor any attachments, it might or might not be useful to report that the user accidentally submitted an empty request. But it is unusual for such a special case to just fall out of a possible alternative semantics of all() and any().True is the identity element for And, similar to how One is the identity element for multiplication.
> all: "there is none in the array that is false"
You... are aware that those statements are exactly the same, right?
But eg Python's minimum and maximum functions don't do that. They throw an error by default.
In mathematical terms, if you have a lattice https://en.wikipedia.org/wiki/Lattice_(order) you can always just arbitrarily introduce a least and greatest element, and all the relevant laws stay valid.
Whether that's a good idea for your application or not, is a different question.
In programming, types often give you trouble. Eg the integers don't have least or greatest element, but you want your minimum function over list of integers to return an integer. So throwing an error is the only choice, if you can't represent something like minus infinity in your return type.
∀x.P(x) is obviously true when the universe is empty -- no counterexamples exist. ∃x.P(x) is obviously not true in that case -- no examples exist.