Abuse of Logic Operators (Short-Circuit) as Control Flow
var x = y || 4;
y = None # y = 4 x = y or 3 print x
mkdir x && cd x
(setq file-name (or load-file-name buffer-file-name))
using “or” for branch control, is a hack abusing a lang design problem of logical “or” and evaluation strategy.
a better name for the typical “or” semantics is “abort-if-true”.
Problem of “or” for Short-Circuit Evaluation
The problem of using “or” as flow control is that it is no longer a boolean logic operation.
For example, if “or” is used as boolean logic, then the compiler can do parallel evaluation on the clauses. But if you are using it as flow control, this cannot be done.
Also, this abuse of semantics forces a round-about way of reading code logic. For example,
x = y or 3
There is the boolean operator “or”. So, you read it as: x gets a boolean value, namely true or false.
But that is not what the code is actually meant to do.
rather, you must read it like this:
x gets the value of, if y evaluates to a value that is considered true, namely, it is not undefined, then, that, else, 3.
Here is what Edsger W Dijkstra has to say about the problem, from a different perspective:
The conditional connectives — “cand” and “cor” for short — are … less innocent than they might seem at first sight. For instance, cor does not distribute over cand: compare
(A cand B) cor C with (A cor C) cand (B cor C);
in the case ¬A ∧ C , the second expression requires B to be defined, the first one does not. Because the conditional connectives thus complicate the formal reasoning about programs, they are better avoided.
— Edsger W. Dijkstra
To many programers, when they learned about
x = y or 3, they think it's cool , because it not intuitive, seems to be advanced knowledge, and is short! To them, they learned a fancy trick! And they proceed to tell everyone to use it as “idiom”.
O god, racket lisp actually has a
ormap. The world is ending.
Programing Idioms and Style
Programing Language Design
- Why I Hate Exceptions
- Iterator, Enumerator, Abstraction Went Wrong
- Should Array Index Start at 0 or 1?
- Syntactic Semantic Difference of Map
- Should Map f Specify Order?
- Abuse of Logic Operators (Short-Circuit) as Control Flow
- Programing Language Idiocy: Bit Operators
- Hack of Bitmask as Boolean Parameters
- Function Dependency