clarification on single assignment
Robert Virding
rv@REDACTED
Fri Nov 24 12:13:26 CET 2000
matthias@REDACTED writes:
>
>The strange thing about pattern matching with records is that no
>pattern matching actually occurs unless you're already in the context
>of another pattern match.
>
>That leads me to wonder how the second '=' in an expression like
>
> A = B#type{name = value} % A unbound, B bound, for this example
>
>can be a pattern match. What are the operator's arguments? What is its
>precedence?
>
>Why* can I write
>
> Value = 3,
> B = #type{},
> A = B#type{name = Value}.
>
>but not
>
> B = #type{name = 3},
> A = B#type{name = Value},
> Value.
>
>Pattern matching is supposed to bind unbound variables. If the second
>'=' really were a pattern matching operator, A would be the same as B,
>Value would be 3. Maybe it's "restricted pattern matching".
The syntax of '=', the match operator, is
<pattern> = <expression>
and the semantics is that you FIRST evaluate the expression THEN you
take the result of that evaluation and match the pattern against it.
It is definitely not the same as '=', the unification operator, in
logic languages. In Erlang there is also the restriction that a
variable must have been bound to a value before it van be used.
DON'T confuse the '=' in records with the match operator, all it does
is couple a field name with a value/pattern. You could use any
symbol there, for example B#type{name |-| 3} or, if you are really
perverse, B#type{name should be coupled to 3}.
So this means that in your last example what you are trying to do is:
B = #type{name = 3},
Create a record of type #type where field 'name' has value 3
and bind B to the record.
A = B#type{name = Value},
Create a copy of the value of B where field 'name' now has the
value of the unbound variable Value.
Value
Return the value of the unbound variable Value.
Which, of course, according to the rules does not work. The first
example, of course, works because you bind the variables before you use
them.
It is actually described quite clearly in the Erlang book, pp 14, 21-22.
This is in the public domain part. Records are described in the
document "Erlang Extensions Since 4.4". Both are available from
www.erlang.org in either PDF os PostScript formats.
Robert
More information about the erlang-questions
mailing list