Search code examples
erlangboolean-expressionshort-circuiting

Evaluation of "andalso" arguments


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?


Solution

  • 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.