[erlang-questions] Variable binding within lists (and tuples)

Joe Armstrong erlang@REDACTED
Thu Aug 6 10:01:53 CEST 2009


You are supposed to think of all the elements in a list or tuple being
evaluated "in parallel"
This is why both [A=2,A] or [A,A=2] are illegal.

Now exactly how they are evaluated depends upon the implementation.

If you evaluate [io:format("a"), io:format("b")] the system will
either print out ab or ba
and the return value will be the list [ok,ok].

if you have a list with function calls [f(...), g(...)] then you're
not supposed to write
code whose correctness depends upon the order of calling f and g.

Now allowing function calls in lists or tuples would be incredibly
restrictive, so it not enforced,
setting up bindings in the different elements of a list or tuple can
be detected at
compile time and is considered an error.

In general we could imagine many different evaluation strategies for
evaluating [A,B,C,...]
left-to-right right-to-left parallel undefined data-flow constrained and so on.

In the old-days of single CPUs left-to-right was the easiest to
implement - on a multicore
you could imagine some kind of parallel evaluation.

Erlang doesn't have an up-to-date formal specification of what-to-do
in such circumstances,
this is rather unsatisfactory.

Suppose we mandated left-to-right, then this would make parallel
evaluation pretty difficult
to implement. If we mandate parallel evaluation then we can't
guarantee that the same program run twice delivers the same results -
the result might depend upon the order of the parallel evaluation.

The approach we have taken is to reject programs that require a
particular evaluation order
of the arguments of a list - so in [A=2,A] or [A,A=2] we can analyse the program
and say that the first list needs left-to-right evaluation and the
second right-to-left.
But we don't want you to write code that depends upon the order of
evaluation, so we
reject both cases.

I think (but can't confirm) that the last version of the Erlang spec
(which is way out of date)
mandated left-to-right so [A=2,A] should be legal, but because we don't want you
to write left-to-write code we forbid it :-)

Robert will correct me if I'm wrong.

Cheers

/Joe


2009/8/5 Zoltan Lajos Kis <kiszl@REDACTED>:
> Hi,
>
> Could somebody explain what is the order of building the list and binding
> the variables in the following examples?
>
>> [A=2,A].
> * 1: variable 'A' is unbound
>
>> [B=2,B=3].
> ** exception error: no match of right hand side value 3
>
> Thank you,
> Zoltan.
>
>
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
>
>


More information about the erlang-questions mailing list