Record selectors

Chris Pressey <>
Fri Jan 3 12:15:26 CET 2003


On Thu, 2 Jan 2003 18:50:14 +0100
"Daniel Dudley" <> wrote:

> I'm curious as to why it is necessary to specify the record
> name when selecting a record instance bound to a variable,
> i.e., Variable#RecordName.Field.

Because Erlang is a dynamically-typed language.  In a dynamically-typed
language, values have types, but variables do not.

> Using an example from the
> Erlang Extensions document, but following good programming
> practice by using a meaningful variable name, we have:
> 
>     > Person = #person{name = "Joe", [0,8,2,3,4,3,1,2]}.
>     {person, "Joe", [0,8,2,3,4,3,1,2], undefined}
>     > Person#person.name.
>     "Joe"
> 
> Since the Person variable is bound to an instance of person
> records, it seems to me that it should be possible to use
> syntax like one of the following examples to retrieve field
> data (and avoid duplicity and unnecessary keyboard typing
> in the code):
> 
> 1)  > Person#.name
> 2)  > Person#name
> 3)  > Person.name

But consider the case of there being another record definition with a
field called 'name', e.g. Country#country.name.  If one were then to write
a function like

  print_name(X) -> io:fwrite("~p~n", [X#name]).

There is no way for the compiler to infer what field #name refers to.

The practical recourse at the moment, at least for me, is:
a) if performance is critical, use records and accept the silly syntax
b) if flexibility is more important, use dictionaries

Quite often I find myself wrapping record accesses in functions, although
"person:name(X)" is just as verbose as "X#person.name" (in fact it's one
character longer :) but it looks nicer, plus it abstracts the access so
that e.g. person:name(X) could be derived from X#person.first_name and
X#person.last_name at some future point in development.  Again, if
performance is critical, this sort of thing should still be avoided,
because unlike "X#person.name", you can't tell what the complexity of
"person:name(X)" is just by looking at it.

-Chris



More information about the erlang-questions mailing list