More general record syntax?

Dowse, Malcolm malcolm@REDACTED
Wed Dec 23 18:49:39 CET 2009



I had an idea about how Erlang's record syntax could be extended. And as
far as I can tell, nobody has ever suggested it. So I was wondering what
people think..


As most of us know, records in Erlang are just a handy syntactic wrapper
for tuples. But, the way I see it, the atom that identifies the record
is used in two different ways. At compile-time, it is associated with a
list of named fields and their defaults. And at run-time it's the first
element of a tuple.


My idea was to allow two different atoms for the two uses. The syntax
could be something like this:


#compile_time_atom/run_time_atom{field1 = val1, field2 = val2, ...}


So, given a record


-record(r, {n, m}).


#r/t{n = 3, m = 4} would evaluate to {t, 3, 4}.

#r{n = 1, m = 2} would mean #r/r{n = 1, m = 2}, which would evaluate to
{r, 1, 2}.


pattern matching would work too:


#r/rn{n = N} = {rn, 0, 0}.


Also, to make it even more powerful the run-time atom could probably
also be a variable (though I can't imagine it being used very often):


#r/Rec{n = N, m = M} = {rec_name, 3, 4}


The main reason I'd find the above change useful is that when
hot-upgrading a gen_server, the state record definition can change.
Since you can't have two different record definitions (old and new) with
the same name, you have to go mucking around with the internal tuple
representation of the record.


For example, in the old style you would write code like this:


-record(state, {a, b, c}).

% -record(state, {a, b}). %OLD

% ...


code_change(_OldVsn, {state, A, B}, _Extra) ->

    {noreply, #state{a = A, b = B, c = 0}}.



Whereas with the newer syntax, it would be:


-record(state, {a, b, c}).

-record(old_state, {a, b}).


% ...


code_change(_OldVsn, #old_state/state{a = A, b = B}, _Extra) ->

    {noreply, #state{a = A, b = B, c = 0}}.



This example is really simple, but with field defaults and nested
records it could get much more error-prone.


Any thoughts?



More information about the erlang-questions mailing list