[erlang-questions] nested variable assignment : bug or the expected behaviour ?

Richard O'Keefe ok@REDACTED
Tue Jun 26 05:43:33 CEST 2012

On 26/06/2012, at 10:55 AM, James Churchman wrote:

> Small syntax related thing
> If i have a function like :
> f()->[J=100,J].
> Or put in the shell:
> {J=200,J}.

The question came up many years ago about how precisely
evaluation order in Erlang was or should be defined.
It's not just variable bindings: if you write f(X)+g(X)
and both f(X) and g(X) are certain to raise an exception,
which one do you get?

One model: Scheme.  Scheme tries very hard to leave the
execution order undefined.  If I write (list (f X) (g X))
in Scheme I have no idea which function will be called

Another model: Common Lisp.  Common Lisp defines left-to-
right execution.

My recollection was that with exceptions and message
passing and I/O in Erlang, the decision was to follow
Common Lisp rather than Scheme.

Indeed, [io:write(a),io:write(b)] does write ab instead
of the more natural ba (think about how lists work to see
why I said that), and so does {io:write(a),io:write(b)}.

And nested variable bindings per se are not rejected by
Erlang.  Try
> io:write(X=a), X.
Although many people feel that this is very poor practice.

Erlang is stricter than it needs to be to ensure that the
source code has a feasible semantics, but not strict enough
to improve readability as much as some people (including me)
would like.

What exactly is wrong with
f() -> J = 100, [J,J].
J = 200, {J,J}?

> Or any other combination of where i try to set a variable nested
> inside somewhere else, it will say "variable 'J' is unbound" .. is
> this the expected behaviour ?

Yes.  But it's not "nested inside somewhere ELSE"; that _is_ allowed.
It's "nested inside the SAME construct other than a serial clause".

> [
> {1, N1=now() ,0 },
> {2, N2=now() ,N1 },
> {3, N3=now() ,N2 }
> ]

This is tricky enough to deserve a function with a name and a comment
to generate it.

More information about the erlang-questions mailing list