Hacker News new | past | comments | ask | show | jobs | submit login
If-then-else had to be invented (github.com/e-n-f)
414 points by fanf2 on Dec 13, 2020 | hide | past | favorite | 248 comments



I remember there was a paper that tried to compare natural language usage of common programming language keywords to see if they may come up with other constructs to create a programming language that is easier to learn as your first one.

There were a few interesting observations. The one that stuck with me the most is that 'and' is most commonly used with almost the opposite sense in natural language vs programming: more precisely, in natural language, 'and' usually implies set union, which is more similar to boolean Or. For example, 'women and children' means of course 'if X is a woman OR X is a child'.

The other interesting observation was that in natural language we usually describe operations on sets as taking the whole set as an argument, not in terms of what happens with each individual member. For example, it's more likely you'll say something like 'give candy to these kids' or 'wash these cars' than 'give a piece of candy to each kid' or 'wash each of these cars'. Of course, index based loops are essentially never used in common language, but even the common loop comprehensions that introduce a loop variable are quite far from natural language.


The word “and” in English is simply there to join multiple clauses together. Whether it is a set union or set intersection, (or some other relations) depends on the sentence.

Set union: they can read and write’

Set intersection: my jeans were creased and dirty

Sequential: he turned round and walked out

Causal: there was a flash flood and by the next morning the town was under water’

And, there are many more usages.


This is correct. The technical word linguists use for the role words like "and" play is coordination.

https://en.wikipedia.org/wiki/Coordination_(linguistics)


I would say that in every case there is a set of things (maybe with a single member) and a set of predicates (maybe with a single member), a mapping from the things to the predicates, and every mapping produces a true proposition.

"Women and children were present" isn't saying the intersection of the women and children were present but that the things were women and children and they all were present.

The rest of the variety of "meanings" of "and" are just inferences on top of this basic meaning. If things occur in sequence, for instance, we can infer causality from what we know about the things conjoined apart from the conjunction.

Crucially, there is more here than just "joining multiple clauses together" (and many of the things conjoined aren't clauses), because "or" can be described this way too, but "and" does not mean the same thing as "or". With "or" you are only asserting that some of the propositions are true.


The meaning of “and” in natural language predates the meaning of “and” used in logics and set theories. I’m not convinced that all semantics of “and” can be derived from set operations.

1) not every clause is a predicate and applying logical operators to a non-predicate makes very little sense to me.

2) I don’t see how ordering, time, and causation can be inferred, if you treat each clause as a predicate.

“I punched Bob and apologized” has a different meaning than “I apologized, and punched Bob.”

The AND as used in logics simply doesn’t embody this usage.

—-

It was a sloppy wording of mine to say that AND just join clauses together. I meant to say that it joins clauses together, and the relations between the clauses are not necessarily set union. Of course it can’t embody all relations, but more than set unions.


I'm being a little sloppy in my language as well.

Since words and phrases necessarily occur in sequence, if you are speaking of things can be and typically are in sequence, it is natural to infer that the speaker is presenting them in the sequence of their occurrence. The speaker can do this, the speaker and the hearer both know that the speaker can do this, and it is a common understanding between the speaker and the hearer that the speaker intends the hearer to receive a particular representation of events: this is the purpose of communication. This being so, the speaker presenting events out of their temporal sequence would be perverse. If the speaker knows the hearer will assume she is presenting events in their temporal sequence, she must present them in this sequence or explain that they are not so presented. To do otherwise would be understood by the speaker and hearer as deliberate deception.

So the sequence comes not from the semantics of "and" but the pragmatics of speaking itself. In fact, you don't need "and" at all. If you leave "and" out -- asyndeton -- and list things, they will be understood to be in temporal sequence if they are the sort of thing that occur that way. "I opened the door. I went out."

All of these "meanings of and" can be explained via pragmatics and a very simple meaning of "and". The meaning I provided was intended as a hand-wavy gesture in the direction of a more formal theory.


> I’m not convinced that all semantics of “and” can be derived from set operations.

Totally agree. I think part of the issue is that "natural-language and" behaves differently when you apply it to different parts of speech, and everyone in this thread is thinking of a different part!

That being said, in the example sentences you gave ("I punched Bob and apologized" vs. "I apologized and punched Bob"), it's actually ambiguous whether they have equivalent meaning or not, when we ONLY consider grammar. Using ONLY the words in the sentence, the relationship between "apologized" and "punched" rests on our interpretation of "and"'s grammatical role. Taken in its usual sense as a conjunction, the two verbs are only related in the sense that the same subject performed them.

But I think you're arguing that "and" places the two verbs in sequence (which prevents the sentence from being flipped without changing meaning.) The more I think about this, the more I don't think it follows. To read the verb phrase this way, the reader has to infer a missing conjunctive adverb: ("punched Bob and [then] apologized")... and in order to make that inference, you need context from the sentence.

To make matters more complicated, we _could_ interpret the sentence in a way that doesn't imply the verbs are related: suppose the speaker is apologizing to some third party, and punches Bob for some unrelated reason. If we interpret it this way, the two sentences can be switched without changing the meaning too much.

But all this just goes to show: your core point is correct: natural languages aren't formal languages, and trying to treat them as such is an exercise in frustration.


> The meaning of “and” in natural language predates the meaning of “and” used in logics and set theories

Yes and it's usually very hard to summarize what words can mean in different contexts, therefore it's usually harder to learn natural languages than programming languages. For example, in a programming language "while you're out, pick up some milk" would be an infinite loop. I think this is why Alexa, Google Assistant, Siri and many more are only finding usage for the simplest of tasks.


"(Women were present) and (children were present)"


How would you distribute "Jack and Jill play together."? If you start introducing prepositions, then your theory of "and"-expansion is going to get quite complex as it covers more and more cases.


Isn't this basically proper nouns implicitly creating a set of size 1?


Short would be, 'and' implies, coincidence, not causality. 'Or' implies choice. If-then implies causality ("If my pants are dirty, then they need to be cleaned")

The big difference I see is with 'OR' in programing the options are exclusive. Ex: "Are you tired or hungry" The answer is yes if you are tired. Yes if you are hungry, Yes if you are both. No if you are neither. This is natural English. In programming if you are both. The answer is No.(False)


Isn't OR in most languages non exclusive? If you want exclusive OR you use XOR.


How is your set union example not another intersection (your quantification could go in one of two places though, they = (set of readers) cap (set of writers) versus they = { p in people such that (p writes) cap (p reads) }.


> they can read and write

Note that I’m not joining people with AND. I joined abilities.

For instance, to expand on the example.

I have three Pokémons. They can read and write.

I’m not saying that my three Pokémon are the intersection of reading Pokémon and writing Pokémon. There might be other Pokémon who can do just the same.

I’m saying that what they can do is a union of writing and reading.

EDIT: spelling


But they are in the intersection of "entities that can read" with "entities that can write".


Yes having attributes containing the union of the sets of attributes {“can read”} and {“can write”} means being in the intersection of the set of things having the attribute “can read” and that having the attribute “can write”. Set union, intersection, and membership are related that way.

(Which means saying that “and” is about intersection and not union is nonsense, everything statement about set union can be rephrased to an equivalent statement about intersection, and vice versa.)


Yeah, there's some duality there. If each predicate is identified with the set of things that satisfy that predicate, then the "and" of two predicates is identified with the intersection of the sets that satisfy the two predicated. On the other hand, if you instead use predicates by talking about the set of predicates that objects satisfy, then saying that something satisfies one set of predicates, and satisfies some other set of predicates, then that says that the thing satisfies all the predicates in the union of those two sets.

For some relation R between elements of the set X and elements of the set Y (we can think of X as being the set of individuals, and Y as being a set of elementary unary predicates), for each x in X, we can refer to A(x) := {y in Y : x R y} , and for each y in Y we can talk about B(y) := {x in X : x R y} . When we say (x_1 R y_1) && (x_1 R y_2), this is equivalent to both (x_1 in B(y_1)) && (x_1 in B(y_2)) i.e. (x_1 in (B(Y_1) intersect(B(y_2)))) , and also to (y_1 in A(x_1)) && (y_2 in A(x_1)) , i.e. ({y_1} \subset A(x_1)) && ({y_2} \subset A(x_1)) i.e. (({y_1} union {y_2}) \subset A(x_1)) .

Personally, if we are talking about a single x_1, and we are saying "and" about a number of different y_1 , y_2 , etc. , or if we are talking about each x in some collection but are saying the same thing about each of them, namely that for each x in the collection, that x R y_1 and that x R y_2 and that x R y_3 , I think it seems more natural to take the first of the two framings described above. That is, I think it seems more natural to say that for each x in the collection, that x \in (B(y_1) intersect B(y_2) intersect B(y_3)), rather than saying that ({y_1} union {y_2} union {y_3}) subset A(x) .

Or, if we give the name W to the collection we are talking about, we could say that "W subset (B(y_1) intersect B(y_2) intersect B(y_3))". This seems to me a fairly natural way to say "all the W , y_1 , y_2, and y_3" ("each of my 3 pokemon can do reading, writing, and arithmetic") .

The other way would end up more like, "({y_1} union {y_2} union {y_3}) subset (the intersection over all x in W, of A(x))".

This works, but seems less natural to me.

Also, especially in the case where you expect X to be substantially larger than Y.


"I have three Pokémons. They can read and write." cf: I have three Pokémons that can read and write.

Now, thanks to what I can only describe as the implicit vagaries of English, the bounding (three) might now imply that I have three ... or more Pokémons! To make that sentence precise: I have three Pokémons and they can read and write. Here I am substituting and for a full stop (period.) When I deployed "that" I managed to muddy the waters.

Mapping logical and Boolean operators to grammatical constructs is tricky and should not be taken lightly. Best to consider them separately. AND is not and (except when it is!)

Be careful out there kids.


It depends if you consider the implied set to be the people (of which there are readers and writers) or the capabilities (reading and writing).


>> Set union: they can read and write’

>> Set intersection: my jeans were creased and dirty

IMHO those are both unions. One describes two capabilities people have while the other describes two conditions some clothing has.

They both become intersection when using the pair of conditions as selection or decision criteria.

It's the difference between an assertion and a question.


To join like constituents, not just clauses, as per your examples.


It's surprising how often you can replace 'but' with 'and' in a sentence.


Why is that surprising? They have exactly the same meaning; the difference is that 'but' additionally carries information about the subjective point of view of the speaker. (Where 'and' indicates that two things are true, 'but' indicates that (1) two things are true; and (2) the speaker considers this surprising or anticipates that the listener might find it surprising.)


coordinating conjunctions are wierd. and, or, for, but, yet, so, nor. Nor is sort of an oddball there, since it continues negated clauses, well I use it to. - my jeans were neither creased nor dirty. Yet fits in a ton of places as well.


Great observations. In the same idea, "or" is inclusive in all of programming and CS, i.e. A and B => A or B, but in natural languages (as least the ones I know) "or" is almost always exclusive, i.e "do you want to eat pizza or pasta?" does not imply that eating both is an option.

This is of course related to why the famous joke "Is it a boy or a girl? Yes." is so hilarious.


If you say it out loud, you will realize that the question "Do you want to eat pizza or pasta?" (exclusive-or case with the answer "pizza" or "pasta," i.e. in the sense "these are your two choices, which would you prefer?") is an entirely different utterance from "Do you want to eat pizza or pasta?" (inclusive-or case with the answer "yes" or "no," i.e. in the sense "would you like to go to an Italian restaurant?"). The first case is pronounced with primary stress on the first syllables of both "pizza" and "pasta," and with a high tone on "pizza" and a low tone on "pasta," indicating a contrast between the two alternatives. The second case is pronounced with primary stress on the first syllable of "pizza," secondary stress on the first syllable of "pasta," and a uniform tone over the phrase "pizza or pasta" on which is superimposed the rising tone on the last syllable of the sentence indicating a yes/no question. (To see that the latter is true, add "tonight" to the yes/no sentence - "would you like to eat pizza or pasta tonight?" The tone does not rise until the syllable "night.")

You have to be very careful in reasoning about natural language based solely on the written record, since spoken language regularly includes features, such as the suprasegmentals (stress and intonation) in the above examples, that aren't recorded in the orthography.


The first one is not exclusive-or, though: if you wanted to eat pizza and pasta, you would not answer "no" to "Do you want to eat pizza or pasta?", you would answer "both". Rather, "or" is serving as a inclusive-or with (perhaps) the incidental implication that picking more than one doesn't make sense in the first place.


Do you want to eat pizza and garlic bread? - inclusive

Do you want to eat pizza or garlic bread? - exclusive

In natural language "and" works like a inclusive or. If there is pizza and garlic bread I can choose to eat one or both. Or is always exclusive in this sentence.


With minor modifications, it can become inclusive or:

Do you want to eat some pizza or some garlic bread? - probably inclusive or

Also, I would interpret the first question as "addition" (pizza with garlic bread, on the model of mac and cheese), not as an inclusive or.


>inclusive-or case

I used to drive my friend crazy when he would ask if I wanted a peanut butter and jelly sandwich or a ham and cheese sandwich and I would answer yes.


He should have given you peanut butter, and a cheese sandwich


To make things even worse, we sometimes capitalise these words to emphasise that we're using them in a technical sense, but OR reads as if it's emphasising that it's an exclusive 'or'. You can have tea OR coffee is clearly emphasising that it's an XOR operation.

Somewhat related: the Ada language uses and, or, xor for its logical operators, but uses and then and or else for the short-circuit forms. [0] Not a very natural solution in my opinion.

[0] https://en.wikibooks.org/wiki/Ada_Programming/Operators#Shor...


VB.NET also uses “OrElse” and “AndAlso” for short-circuiting. VB6 didn’t support short-circuiting at all.


Good example, I'd forgotten about that.

On second thought I was mistaken about the example I gave. If someone says You can have tea OR coffee they're really expressing a NAND. You can have at most one out of the two options. Unlike with XOR, you're permitted to have neither.

To express XOR, you'd need to say You must have tea or coffee.


Latin has both in inclusive ('vel') and exclusive ('aut') or.


"This is of course related to why the famous joke "Is it a boy or a girl? Yes." is so hilarious"

Only to IT people though. Common folks will just look at you in a weird way...


Except the folks are mathematicians.

But in this case there is actually a slight chance that nobody recognizes this as a joke at all...


I knew that someone would point that out..

But I figured most mathematicians are IT people, too. But there is at least also a third group: philisophers. They have formal logic, too (in university), but seldom math.

So in the spirit of the joke:

"Only to IT people though. "

Would have to be:

"Only to IT people and/or math people and/or philosophers, though. "

Desire for formal correctness satisfied?


It can also be used as the equivalent to a try/catch statement in most Germanic languages (including English, though Ingveonic, really) when ending a sentence with it.

"Do you like pizza, or?"

Depending on the exact statement, you might catch more or less flak.


> "or" is almost always exclusive, i.e "do you want to eat pizza or pasta?" does not imply that eating both is an option.

English is way too ambiguous for this example and often relies heavily on context. Wanting to eat pizza does not preclude also wanting to eat pasta. If it was exclusive or, and you wanted to eat both pizza and pasta, the honest answer to this question would be "no," but what you should say is "yes."


I'd say all languages work like that, not just English. Your phrasing "too ambiguous" is a little off to me. Ambiguity (in the sense of utterances having multiple possible interpretations) is the norm in natural language, and it combines with our ability to effortlessly pick the intended one based on context to make natural language work.

Even sentences that on their face are strictly propositional will, in actual situated language use, have implied meanings (a pragmatic level). The canonical example is where one person says "It's cold" (at it's core a statement of fact), after which another person closes a window, or hands them a jacket, or follows with "Let's go home, then". If you want to give an account of natural language meaning that's even remotely complete, you cannot stop at what's in the sentence at the surface, you absolutely have to look at why it's being said.

Indeed, if you think of an actual situation where someone would say "do you want to eat pizza or pasta?", I think you'd find that it does, in fact, imply that the two are exclusive in that context - say if you're at a restaurant where they only expect you to order one main course. But this is not a problem at all, it's just how language works.

(And personally, on the subject of logic and language, I'd even go as far as to say that logic is based on natural language rather than the other way around, but I think that might be tough sell to the mathematically minded.)


>> Indeed, if you think of an actual situation where someone would say "do you want to eat pizza or pasta?", I think you'd find that it does, in fact, imply that the two are exclusive in that context

It was actually this specific question that made it clear to me that this is not the case.

In order to narrow down our takeout options, the girlfriend and I regularly ask questions like, "Do you want pizza or pasta?" meaning "Are any or all of these meal options acceptable to you?" (at which point the conversation continues with maybe us listing a few restaurants which offering one or both options.) This is the same exact phrase, but from context it is inclusive or.

>> - say if you're at a restaurant where they only expect you to order one main course.

Indeed, if the question was something like "Would you like soup or salad?" where, from context, the choice is binary and exclusive.


What is wrong with a yes response to "do you want to eat pizza or pasta?" with yes implying that one would be willing to eat either rather than requiring an exclusive preference that could be asked with "either" before pizza? Similarly with the boy or girl question, "no" may be stillborn.


> What is wrong with a yes response to "do you want to eat pizza or pasta?"

It doesn't answer the question. The questioner is asking for your help in making a decision. If you are completely neutral about the two, then most people answer with the phrase, "Either one is fine". Saying just "yes" sounds like you misunderstood the question --- unless you say it with a wry smile, showing that you mean to be funny in your answer.

(I suppose occasionally someone could ask the question with a different inflection, with the last word at a higher pitch, meaning, "Are either of these fine with you?" rather than, "Please pick one.")

> Similarly with the boy or girl question, "no" may be stillborn.

The sex is set at conception.


Completely off topic, but this is a pet peeve of mine:

> > Similarly with the boy or girl question, "no" may be stillborn.

> The sex is set at conception.

Not necessarily - at conception, the cells could be XX, XY, but also XXY (not to mention, they could be X- or -Y). After conception, chymerism could occur, where XX and XY twins become conjoined and a single fetus develops having both XX and XY chromosomes in different parts of the body - the sex will mostly be determined by which DNA is used when forming the gonads. It could also end up developing both kinds of gonads. But even if the fetus develops testicles, there is a chance that it has some kind of testosterone resistance and ends up with a completely female phenotype. Of course, there is also a possibility that no gonads are developed. This is all staying well in the realm of biological sex, and disregarding other hormonal complications that could happen based on what the mother is doing and her health, and disregarding any morphological abnormalities that could cause surface-level confusion between biologically male and female sexual organs.


These are edge cases, abnormalities. Do you have this pet peeve with other topics? ("If you press the gas pedal, the car will accelerate --- unless you're out of gas, the fuel line is broken . . . ")


One way to make the or inclusive is to use the construct and/or.


This may be why interrogative programming never caught on.


> For example, it's more likely you'll say something like 'give candy to these kids' or 'wash these cars'

That's one of the reasons I like functional programming. In ML-style languages you have something like `Set.map giveCandy kids`, which is both concise and close to natural language.

Comprehensions are also cool in my book, because they're very close to set-builder notation.


> in natural language, 'and' usually implies set union

well, sometimes it can be syntactically ambiguous too, right?

e.g. "I welcome big and small dogs" vs "I welcome well-behaved and properly groomed dogs"


Regarding 'and', it's just that the implied order of precedence is crucial to the meaning. Compare:

(I ate all the chocolate candies) and (I ate all the waffles)

I ate everything that was (chocolate candy and waffles).

In the first example, the intersection is in the set of things that happened. In the second, it is in the set of things.

It's merely a convention that "I ate all the chocolates and waffles" means the first of these while "I ate all the chocolate waffles" means the second.

This is similar to how even if means "power" unambiguously, 2 3 5 doesn't mean one thing until you put parentheses in (explicitly or by convention).


I like the use of language in perl and wish it was more prevalent in other languages.

For example instead of saying "if not <condition>" you can also say "unless <condition>" which is more natural imo.


Yes it's a weird feature but I found myself drawn to it. Just like with natural language, sometimes the 'unless' keyword feels like a better fit.

Both keywords work in postfix form, and this is how I usually use 'unless' so it reads more like a sentence.

  do_thing() unless ($a == 1);
  do_thing() if ($a != 1);


This is valid in crystal:

    unless a
        a = 4
    end
    return x unless y
    return z


> For example, it's more likely you'll say something like 'give candy to these kids' or 'wash these cars' than 'give a piece of candy to each kid' or 'wash each of these cars.

True but for more complex instructions, it’s common to say “do these things for that kid, then do that for all the kids”, which is pretty much a for loop. I can’t speak to how common this was in lay speech before programming was common though.

(There was an earlier thread about this but algolia’s search UI suddenly became a pain to use on mobile and it’s too tedious to find.)


>I remember there was a paper that tried to compare natural language usage of common programming language keywords to see if they may come up with other constructs to create a programming language that is easier to learn as your first one.

Wasn't that the goal of Perl? It was inspired from natural language first, not inspired from another programming language first. This is why it's so quick and easy to prototype in it, arguably far easier than any other language. I believe it is the only programming language to be inspired from natural language first.


This use of "and" and "or" was inherited from mathematical logic though. It's not specific to programming languages.


What you're describing seems to come down to the identity

(((w ∨ c) → a) ↔ ((w → a) ∧ (c → a)))

That is, an implication whose antecedent is a disjunction is a conjunction of implications. On the other hand,

((a → (w ∨ c)) ↔ ((a → w) ∨ (a → c)))

That is, an implication whose consequent is a disjunction is a disjunction of implications.


Interestingly your index based loop example is the opposite of how shell scripting works. That is a lot more like a human language in its construct:

   candy | kids
Where candy and kids are self contained programs that already understand the operations which make up candy and kids.


> it's more likely you'll say something like 'give candy to these kids' or 'wash these cars' than 'give a piece of candy to each kid' or 'wash each of these cars'.

Reminds me of APL.

But I'm not sure APL can be considered being close to natural language.


In fact, when propositional logic was first formalised [1] George Boole gave "and" and "or" the same meaning, denoted by the symbol "+".

[1]: https://t.co/nBYXLPidoS?amp=1


What is the name of the paper?


I really want to know too


> we usually describe operations on sets as taking the whole set as an argument, not in terms of what happens with each individual member.

That's something that array languages did right.


"we usually describe operations on sets as taking the whole set as an argument, not in terms of what happens with each individual member"

Doesn't R do it like that too?


There's javascript's foreach, which also gives an optional index. Indices are important to uniquely identify members in case you want non-uniform behavior: for example, "give 3 kinds of candy alternatingly"; element variables in turn are important for behavior that's a function of the member, say when you want to "give candy in proportion to their age".


> For example, 'women and children' means of course 'if X is a woman OR X is a child'.

Well, no, “women and children” alone doesn't mean that, “if X is a member of women and children” means “if X is in women OR X is in children”.

But that's consistent with AND and OR as boolean operators in programming (it's inconsistent with the way &-and-| symbols are used as set operators in some programming languages, though; ∪ and ∩ would be better, but aren't in ASCII.)


> That's just English, right? Except that it isn't. I can't use "else" as a conjunction in normal speech, only in computer programs.

Sure you can!

Shakespeare used 'else' in the same sense as 'otherwise': https://www.shakespeareswords.com/Public/GlossaryHeadword.as...

"else used as a conjunction" https://wordtype.org/of/else

"Or else!" was common speech before computers, and a common vague cartoon/cowboy/sign threat.


There is some anecdotal support for the article's position in a recent [1] article about the origin of the C programming language -- apparently the C predecessor language CPL used "OR" as a keyword where most modern languages now use "else", on precisely these grammatical grounds, as understood by Christopher Strachey.

[1] https://arstechnica.com/features/2020/12/a-damn-stupid-thing...


Yes, that struck me as weird too, that someone would call it incorrect. I'm a native of the United States (the Midwest). I never gave the word a second thought. I was flummoxed by Strachey's remark and flummoxed again by this article's long investigation.


I am the author, and I mean that I can say "or else" in a normal sentence, but I cannot say "else" without an "or" in normal speech in my normal dialect.


Hmmm, thinking about my dialect of English (Lancastrian) I can certainly say else without an or and it doesn't sound unnatural to my ears. Something like "if you're hungry now then I can make you a sandwich, else we'll eat when we get to the pub" doesn't sound more awkward than using otherwise. I can't say whether that's just because the Lancastrian dialect preserves quite a few old fashioned usages that have fallen out of use in "standard" (i.e. southern posh) British English and American English, whether it's common usage in other dialects of British English, or if its just because I'm a programmer. Going to go ask some English teachers!


The consensus amongst the three English teachers I asked was that it should be "or else" or "otherwise" and that it's probably ungrammatical, although none of them could explain why. The one who is also an actor said "it works as a line" and she wouldn't think twice about it in a script or as written dialog. Interesting one though!


It's definitely not ungrammatical. But it is uncommon today, especially in General American English.


I think it's relatively common in british english.

Certainly, from cumbria, it sounds quite natural also.

It's more spoken dialect than written. "What else do you want to do?" etc.


Funnily enough, to me "what else" sounds more like "what would you like to do in addition" as opposed to "what would you like to do otherwise".

Certainly in Australia, "anything else with that" is quite common in shops, particularly in food shops, or pubs. Or at least it used to be be when I was there.


Sure, but if you ask for A, B and C and someone asks "what else?" then they mean "what about things that aren't A, B or C?" It's still the same basic meaning, set complement, but about things rather than logical states.


The question isn't so much whether "else" is used at all, but rather whether it's used as a conjunction. That's why the article author mentioned "or else": here "or" is the conjunction, so that proves "else" isn't fulfilling that role. In this example you gave:

> What else do you want to do?

"else" is acting like a noun rather than a conjunction (compare with "what activity do you want to do?).


Works in my genericsSouthern British english dialect too. Think it might have been dropped in American english where it might be considered quite formal.


You’ve framed it in the article and here again as a correctness issue, but it’s not a correctness issue. It’s fair to say you haven’t heard it, or that it’s uncommon today, but if you use it, it’s not wrong. And people will understand you, even if you do get a sideways glance from some people. You can use “else” without “or”, if you like.

The article was fascinating, especially the historical examples from different programming languages, and I buy the plausibility of a German speaker using “else” this way... I work with German speakers and they do it all the time. From the small amount of German I know, it feels like there might be some parallel with “als”. Another common one they use that’s less common with English speakers is starting a sentence with “Means”, as opposed to “It means” or “That means”. It’s not incorrect, but it does sound different.

I just don’t think the German speaker explanation is the only possible one, because there absolutely is precedence for the English use of ‘else’ as a conjunction. Usage of ‘else’ with ‘or’ also makes some plausible sense here too...


> The article was fascinating, especially the historical examples from different programming languages, and I buy the plausibility of a German speaker using “else” this way... I work with German speakers and they do it all the time. From the small amount of German I know, it feels like there might be some parallel with “als”.

I‘m a native German.

It was certainly not „als“ as this translates to either „than“ as in „more than“ or „when“ as in „when I came home“.

My guess is that the original German text used „falls“ for „if“ and „sonst“ for „else“:

„falls A > 0 dann X“

„sonst Y“


I shouldn't speculate I guess. :) Als sounds like a cognate to else, but maybe it's not related.

Looking up etymology for "else", I see it comes from old High German's "elles". https://en.wiktionary.org/wiki/else#Etymology

> „falls“ for „if“

This one is interesting in the same way that it might lead me to the wrong conclusion. Is 'falls' related to 'falsch' at all? The English 'falls' is used quite differently, though you can start to see the relationship. For example something like "this falls somewhere between the two".

Language is fascinating! I love learning about how the colloquial meanings of certain cognates between languages sometimes have rather different meanings, especially between German and English since English is a Germanic language. It illuminates the interesting path some of my everyday words evolved from, and it's often rather different than one might guess.


> Is 'falls' related to 'falsch' at all?

Nope, according to Kluge's German etymological dictionary, "falls" is from a Germanic root most literally meaning falling (down) (just like English "fall"), while "falsch" is borrowed from Latin falsus, which in turn comes from the Latin verb fallere, to deceive (like "fallacy"). (Wiktionary also traces the two of them to different Indo-European roots.)

There's an interesting side note that German Fall (the origin of "falls") means "case" (both in the grammatical sense, related to noun forms, and in the senses of "a logical possibility" or "a fact": Wittgenstein's Tractatus starts out with "Die Welt ist alles, was der Fall ist" -- "The world is everything that is the case"), and in fact the English word "case" comes from Latin "casus" (originally literally 'fall' as in the act of falling down), and the German use of Fall in the senses having to do with logic and grammar was a conscious loan translation which Kluge says was devised by Christoph Helwig in the 17th century (intending to translate Latin "casus").

Kluge says that the grammatical sense of Latin "casus" for noun cases was itself a loan translation in Latin from the Greek πτῶσις (literally, 'fall(ing)') which was used by "Stoics" to refer to noun forms by analogy with the possible ways that dice could "fall" when you rolled them. (I don't know why the Stoics would have been the first to write about grammar this way, but maybe...) Apparently the word ptosis is now mainly used to refer to drooping eyelids (!).

Anyway, the idea of different ways that dice (or nouns or fate or situations) could "fall" are different "cases" is a commonality among many languages but the relationship is apparently conscious, on the part of educated people like Christoph Helwig who were trying to find ways of translating technical terms.

That also means that if the German programmers in the mid-20th century were trying to translate "falls ... dann ... sonst" the best English translation would plausibly have been "case ... then ... else" rather than "if ... then ... else". :-)

(English "else" is usually used to translate "sonst" in "was sonst"/"sonst (et)was", but "otherwise" is usually used to translate "sonst" as a conjunction. So you could also imagine that the "else" was inspired either by the dialectal form some other people in this thread are mentioning, or by someone who just didn't realize that "otherwise" would be more usual in this context for Americans.)


Furthermore: "otherwise" translates to "andernfalls", which is basically "im anderen Fall" i.e. "in the other case".


I was a linguistics major in college and therefore am a descriptivist, not a prescriptivist about language. When I say I cannot say this, I mean that this construct does not exist in the ordinary dialect that I speak, in the same way that I can say "that doesn't need washed" even though speakers of many other dialects have to say "washing" instead. If it is in someone else's dialect, they can feel free to say it, but my experience is that it is rare.


> If it is in someone else's dialect, they can feel free to say it, but my experience is that it is rare.

Agreed. And this is the reason why use of 'else' in programming languages might not have had to be invented, right?


No. The article goes into great detail on this - if-else as a construct took a lot of iterations to finally appear in its current form. That fact is largely independent of how natural the word 'else' feels. If we used 'otherwise' instead of 'else', the control flow construct still wouldn't have been obvious.


Yes it is clear that the control flow construct was invented in this form, and that programming languages evolved. It’s still true that this use of “else” paralleled use of “else” in English, and that it’s appearance in programming languages, while interesting, is not a “mystery” or a misuse of language that was “invented” by German programmers.


Below is one of the definitions for "else" in the online edition of the Oxford English Dictionary followed by some of the citations. Some are archaic and some are from poetry, but the last two citations seem to indicate fairly recent colloquial usage.

3.a. In another case, under other circumstances; otherwise, on any other supposition; if not. Now usually preceded by or: see or else at or conj.1 6.

a1225 (c1200) Vices & Virtues (1888) 27 (MED) All ȝelief ðu fastliche, elles ðu, ne namann ne mai bien ȝeboreȝen. a1375 (c1350) William of Palerne (1867) l. 1647 (MED) Foule þow me fodest wiþ þi faire wordes, elles had i deide for duel. 1570 T. Tusser Hundreth Good Pointes Husbandry (new ed.) f. 19 Where Iuie embraceth the tree very sore, kill Iuie, or tree else will adle no more. 1590 E. Spenser Faerie Queene i. i. sig. A5v Strangle her, els she sure will strangle thee. 1837 J. H. Newman Parochial Serm. (ed. 3) I. v. 115 Else how should any one be saved? 1873 R. Browning Red Cotton Night-cap Country ii. 115 Boughs above, Darken, deform the path, else sun would streak. 1938 H. L. Mencken Diary 10 Aug. (1989) 112 Black has told friends that this indicates to him that Reed must be a trimmer, else he would not be favored by all parties. 2013 L. Powell Witch Fire xvii. 155 Shut up, else I'll only make it worse for you. Both of you.

And here are a few citations I found by searching at Project Gutenberg:

They were, in fact, beatified bees, who had to be solemnly invited to attend the death mass when the owner died, else they would fly away, refusing to stay.

https://www.gutenberg.org/files/14036/14036-h/14036-h.htm

“now, I hope, my trial is ended; else its length will be, as in some other cases, the worst of punishments.”

https://www.gutenberg.org/files/9414/9414-h/9414-h.htm

It is absolutely necessary that the plate be chemically clean all over, else the film of collodion, upon drying, will split, and the negative be spoilt.

https://www.gutenberg.org/files/52378/52378-h/52378-h.htm


Anti-prescriptivists are a myth. Sure, there are people who are deluded enough to think that they are “descriptivists” through and through, they may even shroud their prescriptivism with relativistic jargon, but the actions speak more than words. I have never seen a human who doesn’t think that some words and grammar constructions are appropriate and some are not.


Wouldn't it be fair to say that it's just a shortened version of "or else"? Just like most programming languages skip "then" in "if ... then" even though it's often required for the sentence to look natural.


Algol was not prone to abbreviation. Algol 58 used "or if," so if they had wanted "or else," they would have used "or else."


Maybe not in your dialect of English, but what about older dialects?

"Pay for your beer. Else, leave this place at once!"


This is a usage that I have no memory of ever encountering in any context other than computer programming. It may be in some dialects, but not in ones I have come in conscious contact with.


Actually, no, you are right: I seem to have received one email message that begins a sentence with "else" in 1996 and another in 2003. So it is not unknown to me, but it is quite rare.


Fascinating. English is not my first language but I thought https://en.wiktionary.org/wiki/what_else_is_new and https://www.ldoceonline.com/dictionary/what-else-can-somebod... are perfectly fine phrases.


That's "else" used as an adverb, not a conjunction. Author is talking about the latter.


Even if it weren’t, that just means we would have called the construct “if-then-otherwise” instead (perhaps abbreviated as othw).


Yup, it grated on me to read that at the beginning.

Though: else as a conjunction isn't quite archaic today. But, it is one of those usages that when I encounter it, I begin to suspect that the document I'm reading is rather old.


I guess the unknown German word mentioned in the post is probably "sonst". It can be translated to "otherwise" or "else". And "wenn...dann...sonst" sounds perfectly natural in German.


Willing to bet it's either "sonst" or "andernfalls"... I'd suspect the latter, the former is a little bit too informal for mathematicians. Both of these are commonly used for case enumerations in math.


As a research mathematician, I happily use "sonst" in e.g. case distinctions (well, in my undergrad lecture notes; papers are written in English ) and wouldn't use "andernfalls" as it is simply too long :-). Moreover, if they had looked up "andernfalls" in a dictionary, they would have found "otherwise" as translation. For "sonst", the number 1 translation in all dictionaries I have around or found online, is "else".

So I firmly believe they used "sonst".


Maybe. On the other hand, "andernfalls" is a bit long as a keyword.


Except that you’d then have to make all the operators postfix to match how German puts the verbs at the end of subordinate clauses :-p

“wenn a b ==...”


ah but it's more complicated because only the main verb is at the end of the sentence, so if you need an auxiliary or you have a copular construction like "ist gleich", you need to split the verb phrase...

in fact, Germans would say (and do say, e.g. in mathematics) "wenn a gleich b" as a shorthand for "wenn a gleich b ist".


Interesting. Seems sorta like the English shorthand "if a less-than b, do this" (as opposed to "if a IS less than b, do this"). "Equal" is almost a different story since it works as a verb as well as an adjective.


Yes, in English has the verb "to equal", which German doesn't. The verb "gleichen" doesn't work, because it means "to be similar to".


Thanks for the insider German knowledge!


That's an interesting and well-researched article. I'd like to put if-then-else in the bigger historical context of "structured programming".

In the late 1960s and early 1970s, it was a big debate if programmers should use structured programming, building programs out of blocks with control structures such as iteration and conditionals. (Earlier programs were built from ad hoc control using goto.) This is the context of Dijkstra's famous "Go To Statement Considered Harmful.

Although structured programming seems obvious now, there was a lot of resistance. At first, people weren't even sure if structured programming could implement all the required control flows, so someone (Böhm–Jacopini) had to prove the "structured program theorem". Languages needed to be modified to support structured programming, e.g. adding block if-else to Fortran 77.

I have to wonder what modern programming debates will seem as obvious in retrospect as the victory of structured programming.


Maybe almost every major advance.

Personally I think it's just that most people are not good at adapting to new contexts that evolve. And people are not really evaluating things rationally. For example, in the beginning those types of programming languages were completely infeasible to implement due to hardware constraints. So people were not used to them. That created a type of prejudice.

Another example. Look at CISC versus RISC. When the context is raw machine code or assembly language, you absolutely want more complex instructions because otherwise programmers are going to a competitor that provides them.

But then when you have high-level languages that part of the equation changes and reducing instructions gives other advantages.

Neural networks might be another example of an advance that was shunned initially.


You can use "else" that way in ordinary speech. "If this then do that else do the other thing" is perfectly legitimate English, just a bit archaic.


Wiktionary has a usage example from 1903, clearly before modern computers but not too ancient.

> 1903, Jack London, The Call of the Wild, Grosset & Dunlap, page 44:

> […] and his first experience taught him an unforgetable lesson. It is true, it was a vicarious experience, else he would not have lived to profit by it.

As an aside there is at least one common word which does seem to have been invented by the software industry: "access" as a verb


> "access" as a verb

The comic Calvin & Hobbes corroborates the novelty of this verb in this strip from 1993: https://www.gocomics.com/calvinandhobbes/1993/01/25


> “... one common word which does seem to have been invented by the software industry: "access" as a verb”

Really? That’s surprising because the French and Spanish equivalent verb (accéder / acceder) is common and has multiple meanings such as “reaching a peak”. I would have imagined this word transferred over in the Norman days.



Wow, interesting.

Maybe it’s because “to accede” is also an English verb but acquired a different meaning from the Latin root.

Acceding to a computer system doesn’t make sense like it does in French or Spanish, so the noun was turned back into a different verb.


> "access" as a verb

But is it pronounced the same way? I stress the first or the second vowel depending on the case.


That's interesting, what accent do you have? In American English I've only ever heard them pronounced the same in noun or verb form.


For me english is mostly a written language, as I speak it very rarely. I think that I speak with a mix of french and spanish accents, incorrectly stressing the last syllables of many words, and pronouncing different vowels using the same sound.


Check out the wikipedia page on initial-stress derived nouns. [1] It's quite illuminating!

1. https://en.wikipedia.org/wiki/Initial-stress-derived_noun


I believe that sentence should read “or else he would have...” to be grammatically correct.


Perhaps by modern usage. This usage sounds fine but dated, it seems that if you substitute 'otherwise' the sentence is fine.


The article acknowledges that.


Based on what, though?


In colloquial english we usually put an "or" in front of else. It really breaks down when you put it in boolean form because the "or" implies other actions when true rather than actions if false. Removing the "or" completely is unambiguous but is antiquated English.

Examples: "Go to college or else work for your uncle"

Turn this into boolean form: "If you go to college then <foo> or else you will work for your uncle"

But the "or" makes the meaning ambiguous: "If it rains then I will work inside or else I will work outside."

It is not clear if this means you will work outside if and only if it is not raining? Maybe working outside is another option if it rains.

Otherwise is far more clear. "If it rains then I will work inside otherwise I will work outside."

Removing the "or" completely makes the statements unambiguous archaic English: "If you go to college then <foo> else you will work for your uncle" "If it rains then I will work inside else I will work outside."

FWIW - I am very glad they chose else over otherwise...


> But the "or" makes the meaning ambiguous

I disagree that or is ambiguous. In English we use or to mean xor, that is one item or the other item but not both. If we want to clarify that choosing both items is an option we use the term and/or.


> I disagree that or is ambiguous

There are examples of inclusive “or” in natural language. When the waiter asks: “Would you like cream or sugar?”, it’s not meant to imply that you should pick only one; it’s fine to answer “both” (example from: https://divisbyzero.com/2009/09/27/is-or-an-inclusive-or-or-... ).


And if you put a comma in, then it reverts it to exclusive or: “Would you like cream, or sugar?” This may depend on locale, however; I’m speaking of Australian English, and it’s possible that in some locales there may be a verbal cue to indicate the exclusive or but that it wouldn’t be spelled in any way. (As it stands, you could still have a pause before the “or” permitting inclusive or with two inqusitive portions: “Would you like cream? Or sugar?”)

This is a large part of why I dislike prescribed Oxford comma, because it undermines this legitimate use of a comma to alter the semantics.


The human language leaves the decision to the executor, dependency injecting an if/else framework into the entity making the decision.


And “or else” has long been perfectly normal (“if a then do b, or else do c”).

See also “elsewise”, equivalent to “otherwise”; use in this construct “if a, b; elsewise, c” is a good deal rarer.

I would commonly speak sentences like “I was not hungry; else would I have eaten it” among family and friends, but not typically among the general public. It definitely feels a tad archaic, or at least highfalutin.


Perhaps the or was dropped for ease of typing, and also readability/parsing?


I'm inclined to suspect that someone who lived during this era had a pretty good sense of how ordinary "else" was at the time.

I would not be surprised to learn that "else" is more common now thanks to programming languages.

> Christopher Strachey's CPL programming language is the grandparent of C and therefore the ancestor of most current programming languages, and he refused to use "else," calling it "ignorantly incorrect English."

Given how hard it seemed everyone who designed languages tried to avoid using the word, it would seem Strachey's view was not uncommon.


It does not even register as “archaic” to me.

Methinks it's rather ordinary.


Indeed it would behoof us not to assay to declare words archaic ere their time


"A bit"? I've never heard that usage in modern English in my entire life. It's 100% archaic, I'd say. Any teacher or writing professor would mark that as a grammar mistake, end of story.

"A bit archaic" would be like writing "threescore years ago" -- not a normal or especially accessible way of writing, but still recognized as valid grammar.


I said I can't say it, not that no one can say it. It is not in my dialect.


I really liked your article, and the evolution of this syntax is historically interesting. But, your article did quite clearly claim that this use of 'else' is not English. You claimed 'else' is not a conjuction, and you called it a 'mystery' why it ended up in a computer programming language. I'm fine with, and actually I support the idea of being descriptivist about language rather that prescriptivist. But your comment here does unambiguously contradict what you wrote in the article...


The co-authors of the ENIAC paper are Haskell Curry [0] and Willa Wyatt. Curry is well known. Wyatt (Willa Wyatt Sigmund), along with other women who worked on ENIAC, is remembered here [1]

[0] https://en.wikipedia.org/wiki/Haskell_Curry [1] http://athena.union.edu/~hemmendd/Courses/cs80/eniac-women.p...


Chinese also has an interesting sentence structure that doesn't quite fit with European languages. In addition to subject.verb(object) form, there is also a kind of topic-comment form that might be reasonable to use in some assertion-like contexts.

    ensure(foo), !empty()
    require(bar), open()
Chinese also has a word that can transform some kinds of statements into a question. `ma` is used to form yes-no questions. Imagine if languages with truthy values required you to use an explicit keyword/character in postfix position to take a non-boolean value and use it in boolean context.

    if predicate:
        pass

    if non_predicate ma:
        pass

To be clear, I'm not actually advocating for such constructs. The topic-comment form breaks down as soon as you want a predicate on multiple objects. The automatic truthy values concept is already falling out of favor in preference for explicit predicates like file_handle.is_open(). I don't actually want to program in "Cobol, but Chinese". But it is interesting to explore the space.


If you want to go further, it sometimes feels like the "who what where" pronouns are like sql prepared statements.

In English, we have question and answer

Q: Where do you want to go for lunch?

A: I want to go to that pub for lunch.

In Chinese you'd say

Q: You want to go to ?? pub for lunch?

A: I want to go to that pub for lunch.

It even works for numbers, like

Q: It is ?? o'clock?

A: It is 7 o'clock.


Bulgarian also has a question particle (li or ли). In many cases questions are phrased by simply inserting “li” next to the focus of the question.


Semi-related: Fortran has a where() and elsewhere() statement for applying a mask to part of an array. e.g.,

    where (C/=0)
        A = B/C
    elsewhere
        A = 0.0
    end
It blew my mind the first time I saw it. I’d never seen else in anything but an if statement before.


Feels like a good place to drop this for anyone who hasn't encountered it: python's loops have an "else"

https://stackoverflow.com/questions/9979970/why-does-python-...


It begs the question: did we search and find the answer of if-then-else, or did we find an answer that was sufficiently likeable and usable- but one of many possibilities? How do we know whether this choice was the global optimum vs a local one?

Is if-then-else the electron- a deep truth waiting to be discovered- or the gasoline powered car- an option we explored for decades among others options.


In regards to global vs local optimum it is useful to look at the alternatives like pattern matching.

For languages that don't support pattern matching or passing in functions as values, "if" is probably the best you can do with. You might be able to do something with boolean short-circuit operators but it's debatable if that that is better than the if statement.

In React, if you are using JSX, they don't have "if" statements within the markup they just use the boolean short-circuit (&&) operator.

For more ML style languages that support pattern matching, it is often easier to express solutions that way than with traditional if statements. In those situations I would say that "if" is less desirable in terms of expressive power and code readability.

Also, "if / else" only supports 2 cases, with pattern matching you can have an arbitrary amount of cases.

Without pattern matching, expressing more than 2 cases becomes a combination of nested if statements combined with "&&" and "||" expressions. This makes it much harder to read and write.


> Also, "if / else" only supports 2 cases, with pattern matching you can have an arbitrary amount of cases.

Coming from a non-pattern marching language (python) I’ve yet to see what the big deal is, maybe you can help.

I can have as many elif’s as I need cases and other than maybe not needing to repeat `x==...` I’m not sure what I’m missing out on.

With that being said, I do often wish for more elegant solutions to long winded if else


To get an intuition for the expressive power you can look up examples of quicksort and factorial in languages that support pattern matching. Haskell is a good example.

It is true that you can always just use if statements, it's more about the convenience and cleaner syntax. You can also do destructuring with pattern matching. Pattern matching is almost a requirement if you are going to use algebraic data types.

As Paul Graham says in Beating the Averages, you have to look at the other language from the perspective of knowing it. Nobody can really explain it. It's just going to seem equivalent or weird syntax otherwise.


Thank you for the thoughtful answer.

It made me rethink the premise of my question.


It is an interesting questions. My feeling is if-then-else falls some where between invented and discovered, something like mathematics. Once we had discovered the need for conditional control flow, any decent assembly language programmers would quickly discover many patterns for how it could be used. Eventually, these patterns were clarified and codified into languages and more abstract formalism. Like in much mathematics, that abstract formalism was am inevitable discovery once we took as axiom the basic logic of program control flow with conditional jumps.

It is such a basic, clear, and useful formalism, it is hard to imagine it not becoming widespread under some name/syntax.

But if-then-else is only clearly inevitable if you take as axiom the existence of store program computers with control flow. I can much more easily imagine that early on we invented a very different way to do computation as a whole. It seems likely that what we have actually invented is on a path toward a local optima.


Is pattern matching a generalization of if/then/else, a reframing of it, or something else entirely?


I see it as a cross between a switch and if statement. You’re saying based on what `x` is (a switch), do these things that a switch can’t do (an if).


If-then-else is pattern matching on a value of type Bool. I think of general pattern matching on algebraic data types as a generalization.


"if then else" is indicative of an underlying pattern that exists at a more fundamental level. In that sense, it was "discovered", not invented.

Depending on the language, the syntax of "if then else" is not needed and is syntactic sugar.

In the Lambda Calculus you can implement "if else" using "first" and "second".

Here is something equivalent in JavaScript.

  const trueFn  = (first, second) => first
  const falseFn = (first, second) => second

  const ifFn = (boolFn, first, second) => boolFn(first, second)
  
  ifFn(trueFn,  'yes', 'no')  // returns 'yes'
  ifFn(falseFn, 'yes', 'no')  // returns 'no'


Not truly equivalent!

let's define `delete(file)`, which returns 0 if it successfully deletes the file, and 1 if there's an error.

ifFn(trueFn, delete('A'), delete('B')) will not do what you want it to.


This is true. In a lazy language it is the same, in imperative languages that do eager evaluation it will indeed have the problem you mention.


I lean toward "if a b c" being a true primitive, due to it being one of the special forms in Lisp. This is necessary to avoid evaluating the arguments in the road-not-taken, without fexprs, and I daresay that would be a distraction at the moment.

It's also embodied in actual machine words. The actual verbiage of "if a then b else c" is clearly less important, C elides the "then" after all.

I'm presuming you mean the construct, not the happenstance of how it's spelled out, because you're clearly referring to the electron, not the word for amber-the-stone which we happened to adopt for it.


The historical truth is that Lisp had COND first; IF was added later. Also, LAMBDA before LET.

MacCarthy writes, in History of Lisp:

I invented conditional expressions in connection with a set of chess legal move routines I wrotein FORTRAN for the IBM704 at M.I.T. during1957-58. This program did not use list processing. The IF statement provided in FORTRAN1 and FORTRAN2 was very awkward to use, and it was natural to invent a function XIF(M, N1, N2) whose value was N1 or N2 according to whether the expression M was zero or not.

Yet, no such thing was added to Lisp, initially. The 1960 Lisp 1 Programmer's Manual only lists COND.


An interesting historical note, but it says nothing about the relative 'primitiveness' of COND vs IF.

It's not uncommon at all in mathematics to build a system with certain axioms, and then improve them later, when it's realized that simpler axioms can be used to build more complex constructs.


Either one of cond and if can be primitive and the other one a macro.


I wondered whether there was a conscious link in the minds of early language designers to Church encoding of booleans. (well, other than McCarthy and Lisp)

A Church boolean is either:

  true = λt.λf.t
  false = λt.λf.f
So instead of writing an expression with keywords like

  if bool then yep else nope
Just use the boolean as a function and apply it to the then and else clauses like

  bool yep nope
So the shape is very similar to modern languages, but with less syntactic scaffolding.


It underlies the decision tree model of computation: https://en.wikipedia.org/wiki/Decision_tree_model


>How do we know whether this choice was the global optimum vs a local one?

By letting anyone free to find a better alternative. Waiting...


This is fascinating!

I started with BBC Basic II (on the Model B) which had IF..THEN but it was just one line and there was no ELSE. So if you wanted to make a 'block' you had to call a different PROC (thankfully there were PROCedures so you could avoid GOTO)

As such when I was introduced to ELSE and ENDIF with BBC BASIC V on the Archimedes it seemed like very welcome syntactic sugar - it let you do the same stuff but in a tidier way

https://en.wikipedia.org/wiki/BBC_BASIC


BBC Basic II does have ELSE, it just has to go on one line.

IF A=4 THEN PRINT "FOUR" ELSE PRINT "NOT FOUR"

Statements for the IF block and the ELSE block can be separated by ':'.

I was recently given a BBC Micro and it's a fascinatingly impressive machine, the hardware and software are so beautifully designed in tandem that it's quite awesome even in 2020.


ah yes you are right, the in-line ELSE

Obligatory shout out for 'Micro Men', about the making of the BBC Micro and ZX Spectrum https://www.youtube.com/watch?v=XXBxV6-zamM


For more geeky insights into the time, I can recommend the book The ZX Spectrum ULA http://www.zxdesign.info/book/ The business side of things is incidental to the rich details of the hardware design and production.


"Else" is not archaic. Every kid growing up in the sixties knew that the way to start a fight was to say "Or else!" It was used a lot in cowboy movies before a gunfight.


I think for these purposes, “else” is different from the “or else” construction.

As in: “Read thee the article, else thou shall suffer great ridicule in the comments.”


"thee" is the dative (and later accusative) inflected form of "thou", the second person singular pronoun.

In your sentence above "Read" is the imperative form of the verb. The subject is elided since it's implicitly second person (singular or plural) (as imperative is used to give orders to people you're talking to) and if it wasn't elided it would have been in nominative case. Middle english had an ending -(e)th to form a plural second person imperative.

"Learn the grammar of past and present languages, else you'll attract pedants from the intertubes"


This is fantastic


(At least a couple of wrong words there: “thee” should be “thou”, and “shall” should be “shalt”. Also I reckon “thou shalt” reads much better as “shalt thou” in this style, though either is acceptable. Final proposed form: “Read thou the article, else shalt thou suffer great ridicule in the comments.” The overall style of the sentence is still rather off for the era, but it’ll do.)


“The best way to get an answer in the internet is not to ask a question, but to post something incorrect.” - Thomas Jefferson


If you are calling me archaic, I'm going to have to ask you to step outside, you young whippersnapper.


The use of the word “else” bugged me enough that when I put together syntax for Kal (now defunct, but here’s a link https://github.com/rzimmerman/kal) I added “otherwise” as an alias. It’s interesting to see I’m nowhere near the first to come up with that!

Some example syntax:

    unless name is 'Steve'
      print 'Impostor!'
    otherwise
      print 'Steve'

“if” and “else” work, too. But I really did like the “unless” and “but” keywords.


This reminds me of a note in FreeBSD rc(1) man page[0] under "INCOMPATIBILITIES"

> The Tenth Edition rc does not have the else keyword. Instead, if is

> optionally followed by an if not clause which is executed if the pre-

> ceding if test does not succeed.

which i found pretty interesting

[0]: https://www.freebsd.org/cgi/man.cgi?query=rc


Having taught programming to novices a little, I believe “if not” is clearer than “else”. Imagining “not” being prepended to the original conditional expression would be natural, especially in languages with “not X” construct (like Python), and it’s easy to forget that “else” is in fact archaic to non-programmer ears, slightly and possibly needlessly raising the barrier.

    if (X) { doY(); }
    if not /* X is implied */ { doZ(); }
In languages like Python it could be generalized to enable one to use “if not” with an expression as usual but omit the expression if it is the last branch of a conditional, thus getting rid of the “else” keyword while maintaining or arguably improving readability.

That said, there is no programming language that could entirely map to a spoken one, so perhaps it’s actually beneficial to shed any semblance of such mapping early-doors in the learning process.


What if there were 3 cases though? "Else" should exclude both of the preceding cases, but the phrasing of "If not" seems to imply it would only exclude the previous case


True!

A point could be made for restricting ifs to 1 or 2 clauses and delegating more complex conditions to switch/case, but that is arguably even more far out there (and in case of Python it actually doesn’t have the switch operator). Also, “if not X {…} if not {…}” would be confusing but possible.

I guess I should leave language design to the better-equipped for the time being.


I wonder whether anyone has used "otherwise" for this. It'd be a simple alias for "else", but it'd certainly sound natural:

    if (X) { doY(); }
    otherwise { doZ(); }


Towards the bottom of the article there is a example of MAD[0] that uses something similar, and there is also the John McCarthy proposal which also uses otherwise. I could imagine it being used in a language that had a tight connection to maths as otherwise is often used there.

[0]: https://en.wikipedia.org/wiki/MAD_(programming_language)


Oh, right, the article...


I remember something like 25 years ago (when I was 8) that the variant of Basic I used did not have a good if-then-else. Instead it was done a lot using if and goto (with line numbers :-))

Some years later in embedded development I learned that this was actually more similar to the CPU instructions used underneath, conditional jumps.


If the question is, what was the first programming language that introduced "If-then-else" then the read makes sense, but I'm not sure if was really an inventive step.

In propositional logic, which was developed well before the first computers by Leibniz, Frege, Boole, De Morgan, etc.:

"If A then B else C" can be stated as: (A --> B) ^ (¬A --> C)

So, in patent/invention language, I'm not sure if it would really constitute an invention since it is just putting a known mathematical formalism into a programming language.

It would be possible to implement this in Leibniz' calculus ratiocinator ~300 years ago: https://link.springer.com/chapter/10.1007/978-3-319-93779-3_...


McCarthy published a paper in 1961 about if-then-else as a form of propositional logic replacing and/or/not, with its own identities playing a role like associativity, de Morgan's laws, etc. This had to be invented.

It's interesting to me that these identities and the canonical form McCarthy introduced there were exactly how BDDs work (when you just add memoizing, which was also invented about the same time) -- but BDDs weren't invented until the 1980s. (Explanation at https://codewords.recurse.com/issues/four/the-language-of-ch...)

It's easy to think things are obvious in hindsight.



Your formula `(A --> B) ^ (¬A --> C)` expands to `¬(A & B) & (A | ¬C)`. I would propose that `(A & B) ^ (¬A & C)`, which expands to `(¬A | B) & (A | C)`, comes closer to actual `if` semantics.


They are equivalent (assuming ^ is the same as &). In particular, A --> B is equivalent to ¬A | B.


I see. I interpreted `^` as XOR. The implication (`-->`) was clear enough to not be misunderstood.


The "ʌ" symbol (^ due to laziness) is commonly used to mean AND in propositional/formal logic in mathematics:

https://en.wikipedia.org/wiki/Propositional_calculus


I know, but due to the use of “¬” for the negation I would have expected “∧” (‘LOGICAL AND’, U+2227), or at least something less ambiguous, like “&”. C conditioned me into thinking of ASCII caret as XOR.


Nice walk through history, interesting to think that at some point if-else was in need of diagrams to describe the concept clearly.

When I ran the "if-else" statement of my programming language* by a user-study with my non-technical brother-in-law he said it reminded him of the binary nature of legalise and inherently limiting the nature of what is possible. I agree.

My sister also formed the study-group and consistently they both prefer "otherwise" to anything else (pardon the pun).

* The language in case anyone wants to take a look: https://github.com/ducklang-community/ducklang


This was presented by the author at !!Con West 2019:

  https://www.youtube.com/watch?v=4A94JsWTXXw


In the MAD example the letter O has a slash through it, and the numeral zero is unslashed. Does anyone know if this was an actual printing convention at one time? It seems backwards from how it's done today.


That was a common convention at the time and you can also see it in early BASIC manuals.


Recognised that GitHub username straight away. That author also made "datamaps": https://github.com/ericfischer/datamaps

I remember over 5 years ago, they helped me me visualise 1 billion "Shazam's" (where I was working at the time) onto map tiles. Glad to see they are still supporting developers!


Thanks. My major public project for map utilities has been Tippecanoe, https://github.com/mapbox/tippecanoe


Fun fact: English isn't my native language and I learned programming before becoming fluent in English. I believed for a long time that 'else' was just a shorter alternative for 'otherwise'. I used to say things like "I'll have apple juice if you've got some, else I'll have orange juice."


This is a totally correct usage, it just makes you sound like a romantic poet or a 19th century orator.


> I believed for a long time that 'else' was just a shorter alternative for 'otherwise'.

It has other uses, but it is that (that is, “or else” is exactly that, and, among other uses, “else” by itself is an accepted short form of “or else”.)


That's valid, if slightly odd, English. More commonly it would be "or else I'll have the OJ".


Fantastic choice of images and linked documents in this article. I learned as much from the linked papers and reports!


Interesting timing. I just read https://arstechnica.com/?post_type=post&p=1728174 due to r/programming https://www.reddit.com/r/programming/comments/kbs11a/a_damn_... yesterday.

Apparently Cambridge Programming Language (more or less a failed language that became proto-C) designer Christopher Strachey had some misgivings about this usage of "else".


Looks like this article was the source of the Twitter thread https://twitter.com/geoffwozniak/status/1337916048276852737 where I revived the discussion of my talk.


Referring to the three-way “FORTRAN” syntax, you say, “The three-way "if" was more powerful than just checking for a negative, but was probably more confusing,” this is not right. As a 15-year-old at Stuyvesant, in 1966, learning FORTRAN 4, I assure you it was the most natural thing in the world. Especially instructive was the fact that usually two of the target statement numbers would be the same. FORTRAN 4 didn’t have Boolean data types, OR, or AND and += was still in someone’s nightmare.

Note also that when Microsoft put IF( , , , ) into Excel, the most widely used computing application in the world, they essentially used this syntax.


Thanks. It has been cited as confusing in sources like The Elements of Programming Style, but I can appreciate that it may feel natural to some people, and there are certainly cases like strcmp() where a three-way distinction is necessary, and current languages lack a good way to talk about it.


I had to check whether my memories of my first programming language (AppleSoft BASIC) were correct and they were: that language did not offer an ELSE statement. There were just IF expr THEN cmd and IF expr GOTO line. I don't remember being shocked or overly impressed by the existence of else when I first encountered it in UCSD Pascal, but I do have vague memories of having to write code in AppleSoft BASIC that either was structured with IF this... IF not this or perhaps IF this GOTO 40, do what would be in the else then goto the line after the code starting at 40, then the code for the if statement.


One of my first jobs was using the IBM mainframe RPG III language in 1985.

About half a year in, and new language version introduced IF/ELSE statements. I was glad to finally get a semblance of modern programming, but the old RPG veterans advised against using it, since the new fancy features often didn't work so well, and anyway you can write anything you want without it.

After 14 months, my contract wasn't extended. Maybe the complaint that I could be seen sleeping at my desk sometimes were a factor.

You young kids don't know how good you have it...


The story of development is interesting, but I doubt that the concept itself needed invention. Even in machine language using nothing but conditional branching the pattern would have appeared enough to be an idiom perhaps without a name:

       ...
       b?  addr1
       ...else stuff
       jmp addr2
  addr1:
       ...then stuff
  addr2:
       ...always stuff
What's more interesting is the generalization to any boolean expression, not the naming/placement of the else/always parts.


Yep. I remember naturally writing assembly like that when I was a kid. When I picked up a high level language if statements were not mind blowing, it was already what I had been doing the entire time.

What did blow me away was seeing a function for the first time.


I learned on 6502 and used jsr/rts (jump-to/return-from subroutine). Recursive functions later in my learning was a mind-blowing moment, then seeing stack frames and call conventions made it less magical.


I miss that. Chaining jump to continue range of memory of jump is fun.

It's all down to comparing hex in 2 registers and jump. JNE, JE, JMP etc.


The logic of deciding on a course of action based on a single determinate decision was not a new concept.

I would think Soren Kierkegaard deserves a hat-tip to his existential work: Either/Or.


I can remember my mom telling me, sometime in the late 70s or very early 80s, that she thought the new version of Fortran was an improvement because it had `else`.


Ah, interesting, I wish the title had been prefixed with "What if ".

There's a language where THEN basically means ENDIF... Forth, if memory serves me right?


Yes, and the inventor of the language eventually removed ELSE from his dialects, amusingly. These days he says that his code has very few conditional statements.

I think the tactic strategy to achieve this is to confine conditional branches in a few well chosen words.

For instance if you have a word SORT that sorts the top pair on the stack, which has to have a branch:

    : SORT 2DUP < IF SWAP THEN ;
then you can build "if-less" MIN, MAX and ABS:

    : MIN SORT NIP ;

    : MAX SORT DROP ;

    : ABS 0 SORT SWAP - ;


Despite my somewhat crippled ability to think RPN, I love the simplicity and expressiveness of the above.


Yes. It is used in the sense of the English statement:

IF you go to the store get some butter THEN come right back.

So THEN is where the program continues on a false condition. Typically Forth. It uses an alternative way of looking at things.


The GForth documentation addresses this. [0] Forth is simply adopting a different use of 'then' than the one more commonly seen in programming languages, but it's still faithful to English.

[0] https://gforth.org/manual/Selection.html

See also the StackOverflow thread on this topic: https://stackoverflow.com/q/12539634/


Yes, Forth is stack-based RPN so "IF" naturally comes after the test; "THEN" marks the end of the block; so if you want "ELSE" it ends up in the middle to let you nest conditions.

    : /CHECK   DUP 0= IF  ." invalid " DROP  ELSE  /  THEN ;
https://www.forth.com/starting-forth/4-conditional-if-then-s...


Just one of those things that no one really questions the existence of. It, like the semicolon, always has been and will be.

Good work digging through these historic esoteric languages. Wikipedia states McCarthy of Lisp fame invented it so many of the evangelists here likely know the conclusion here.


“It, like the semicolon, always has been and will be.”

Not the best of examples. It hasn’t always been. Early fortran and lisp didn’t have it. Reading https://medium.com/better-programming/a-brief-history-of-the..., it seems Algol and PL/I set the trend to make it popular.

Looking at newer languages, I also get the impression it’s on the way out. Rust has them, but python, scala, go and swift try to avoid them (https://python-reference.readthedocs.io/en/latest/docs/opera...: “Avoid having multiple statements on a single line. Though the language definition allows one to use a semi-colon to delineate statements, doing so without reason makes one’s code harder to read”, https://golang.org/doc/effective_go.html#semicolons: “Like C, Go's formal grammar uses semicolons to terminate statements, but unlike in C, those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them.”, https://docs.swift.org/swift-book/LanguageGuide/TheBasics.ht...: “Unlike many other languages, Swift doesn’t require you to write a semicolon (;) after each statement in your code, although you can do so if you wish. However, semicolons are required if you want to write multiple separate statements on a single line”)


Semicolons came in with Algol 58 too, which used them in what now seems like a really excessive way.


You don't need "else".

  if (x) then: doSomething();
  if (!x) then: doOtherThing();
"Else" is a redundant construct, but it's nice to have for sure. I would prefer not writing the above code.


This doesn't work like "else" if doSomething() can change the value of x.


That's true! You could cache x as a constant beforehand, but again super ugly.


I'm imagining what programming languages look like if the Axis powers won WW2. We might get many forth-like languages instead of C-like ones, since Japanese and German have subject–object–verb order.


German is generally subject verb object.


The language REBOL used `either [] []` which I now miss regularly.

It was great in that by default it pushed to me consider and deal with `else` in every case.

There are allot of bugs left when stopping at 'if'.


A new REBOL like language is in the making:

https://www.red-lang.org/

Definitely worth a look.


I would love to read something similar about a "for" loop. "if/else" always sounded natural to me, but a "for" to mean a loop never did.


I bet it's from maths. "For k in Z, ...". But in programming, imperative is more useful than declarative, so we turned this into "For k from 0 to ...", as it translates directly to telling the computer what to do - and this is the form most programmers ended up being exposed to.


For is also from Algol, replacing "do" from Fortran. I agree it would be interesting to know why the word was chosen, but I think it comes from the mathematical "for all x in Y, x > 5" or whatever other assertion is being made.


I love reading these old manuals; so many of them had hand-written symbols (eg ->) that couldn't be expressed by whatever typesetting system they used at the time.


If/else is just as made up as for loops - it’s all if/goto underneath.


Unless you compile your program with movfuscator: https://github.com/xoreaxeaxeax/movfuscator

Or you decide to execute code on The Fungus: https://www.bedroomlan.org/hardware/fungus

I also recall reading a paper that got into implementing a GC on silicon for a graph rewriting based architecture

WebAssembly is if/else blocks. There's a potential future where it gets implemented directly as a CPU ISA (albeit it'd likely involve some dynamic translation, but the CPU may decide to have SSA as its internal representation)

It's important to understand there's a real distinction between semantics & implementation. Otherwise you risk emulating your implementation when some new hardware comes out (say GPUs, or Quantum computers, or out of order CPUs working backwards to create something like SSA for register renaming/pipelining, or cmov)

See also the debates over C code being executed in the C abstract machine for optimizers while programmers rely on implementation of the end result. But in a language without undefined / implementation-defined behavior you won't have these ways of having the program self observe its implementation


> I also recall reading a paper that got into implementing a GC on silicon for a graph rewriting based architecture

Not that, but still interesting: the Intel iAPX 432[0] was a (failed) processor from 1981 designed with high level languages in mind (specifically Ada). It supported bit-level aligned, variable length instruction, but also a built in GC and type tagging system.

[0]: https://en.wikipedia.org/wiki/Intel_iAPX_432


> I also recall reading a paper that got into implementing a GC on silicon for a graph rewriting based architecture

Maybe this one:

https://github.com/tommythorn/Reduceron


That's the one. Gets me breaking out in a solid minute of laughter imagining C code that thinks its "close to the metal" being compiled to that


Pretty sure at least 90% of the readers here know that, but still appreciate the convenience of higher-level language constructs. That's why they're called "higher-level" after all.

BTW, it's not entirely correct that it's all if/goto. ARM has conditional execution that doesn't necessarily involve a jump, and there have been other exceptions as well.


x86 has CMOV, for Conditional MOVe, since the Pentium Pro, and of course there are tricks employed by compilers and low-level programmers to avoid the overhead of branches, like the `a = cond·b + !cond·c` idiom.


Interestingly, in logic programming languages if/else sometimes turns into arithmetic, so (slightly simplifying)

'if x then y else z' becomes 'xy + (1-x)z', or 'x*(y-z)+z'


I remember first coming across "for"; the ... parsing of it in my brain I don't think ever did make it. I had to just accept it for what it was.


It was discovered not invented. All sentient beings will have if-then-else.


  Jump or not jump
    Jump or not jump
      Jump or not jump
:out_of_range

:the_end


English had to be invented


That was a fun read. Was that original research? Great job if so.


It just sounds like a simplification of "if a then b, in all other cases c"




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: