I love the idea of short circuit evaluations. Took me a while to figure out why a piece of code wasn’t working–short circuit evaluation documentation in the Manual section lacks clarity when using an assignment on the right.
Failing code:
n = 1
n < 1 && n = 5
Gives:
ERROR: syntax: invalid assignment location “(n < 1) && n” around REPL[11]:1
Stacktrace:
[1] top-level scope
@ REPL[11]:1
I would like to see an addition to the short circuit documentation clarifying the use of an assignment on the right side. Something like:
When using an assignment on the right side of a short circuit evaluation, the assignment statement must be enclosed in parenthesis.
n = 0
n < 1 && x = 5 # Incorrect
n < 1 && (x = 5) # Correct
(n < 1) && (x = 5) # Correct
However, at first glance, the reader might see this as a logical “and” operation and interpret the flow of the statement incorrectly.
I personally would suggest dropping the “||” short circuit and using something such as the keyword “then” in place of the “&&”. In my mind, this leads to a clearer understanding of the code’s function. It might look like:
n < 1 then x = 5
The false logic can be accommodated by
!(n < 1) then x = 5
Just thinking…