Record selectors

Daniel Dudley <>
Sun Jan 5 11:43:37 CET 2003

This thread has generated some interesting replies, but I'm
left wondering whether I have been entirely understood.
Here's a sample test module, which I hope will help clarify
my original message:


    -record(person, {name, phone, address}).
    -record(country, {code, name}).

    selector() ->
       Person = #person{name = "Joe",
                        phone = [0,8,2,3,4,3,1,2]},
       Country = #country{code = 47,
                          name = "Norway"},

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

Note the reference to a country record in print_name/1
(using the prescribed record selector syntax), and the
result of the following dialog:

    1> c:c(test).
    2> test:selector().

The call does not produce an error or
failure because the name of the country record's second
field is 'name'. Consequently, the value of the second
field (third element) in the X variable, which is bound to
a person record, is returned.

This example illustrates that not only is the reference to
a specific record-type in the record selector syntax
superflous, it is downright "dangerous" because it invites
error-prone code.

The bottom line is that a record selector is tied to the
type of value stored in the variable being investigated. If
this type is (as expected) a tuple, then the actual record
type is (must be) determined by reading the first element
of the tuple. Only then can one decide which of the
remaining elements in the tuple corresponds to the
specified field.


More information about the erlang-questions mailing list