Evaluation of "andalso" arguments

168 views Asked by At

I am new to erlang and I tried the following in the erlang shell:

1> ((Var1 = 13) == 13) andalso ((Var2 = 12) == 13).
false
2> Var1.
13
3> Var2.
* 1: variable 'Var2' is unbound
4>

Why is the Var2 variable not bound to the value 12?

2

There are 2 answers

0
Pascal On BEST ANSWER

E1 andalso E2 (since R13 i think) is equivalent to

case E1 of
    false -> false;
    _ -> E2
end;

compare to this definition I agree that Var2 should be bounded in your case.

But in general, you have no guaranty that E2 will be evaluated, so it is really unsafe to assign a value to any variable in E2.

I tried to follow the parsing of the expression in erl_parse, but I can't say if this behavior is made on purpose or not.

11
I GIVE TERRIBLE ADVICE On

This sounds like a bug in the Erlang evaluator. The compiler actually refuses to let this go through. Compiling this:

-module(t).
-compile(export_all).

main() ->
    ((Var1 = 13) == 13) andalso ((Var2 = 12) == 13),
    {Var1,
     Var2}.

Yields:

t.erl:7: variable 'Var2' unsafe in 'andalso' (line 5)

Which tells you that in case the left-hand side expression would fail, the code couldn't go through as expected.

That the shell lets it go through means the evaluator running there does not properly match the compiler. It might be worth reporting to the OTP team on erlang-bugs.