[erlang-questions] Comparing (pattern-matching) records

Joe Armstrong erlang@REDACTED
Sat Mar 31 10:06:03 CEST 2012


You wrote

> #rec{} = #rec{a=1}.

When used on the righthand side of '='
#rec{} is a constructor which creates a new record.
On the left hand side of '=' #rec{} is a *pattern* the above line
means the same as if you had written:

> #rec{a=_,b=_} = #rec{a=1}.

In a record pattern you only need to include the
tags you want to constrain.

So

> #rec{a=1} = #rec{}

Means the same as

> #rec{a=1,b=_} = #rec{}

The RHS is a constructor and evaluates to
#rec{a=1,b=undefined}


The Lhs is a pattern and the match works.

/Joe




On Sat, Mar 31, 2012 at 9:37 AM, Avinash Dhumane <avinash@REDACTED> wrote:
> I might have overlooked all the 3 books (for sections on records), but
> couldn't find an explanation why a pattern matching error doesn't occur in
> the last (7th) shell expression below.
>
> Please.
>
> Thanks.
>
> $ cat rec.hrl
> -record(rec, {a, b}).
> $ erl
> Erlang R14B02 (erts-5.8.3) [smp:2:2] [rq:2] [async-threads:0]
>
> Eshell V5.8.3  (abort with ^G)
> 1> rr("rec.hrl").
> [rec]
> 2> A=#rec{}.
> #rec{a = undefined,b = undefined}
> 3> B=#rec{a=1}.
> #rec{a = 1,b = undefined}
> 4> A=B.
> ** exception error: no match of right hand side value #rec{a = 1,b =
> undefined}
> 5> {} = {1}.
> ** exception error: no match of right hand side value {1}
> 6> {rec, undefined, undefined} = {rec, 1, undefined}.
> ** exception error: no match of right hand side value #rec{a = 1,b =
> undefined}
> 7> #rec{} = #rec{a=1}.
> #rec{a = 1,b = undefined}
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list