[erlang-questions] Dynamically access record fields

ok@REDACTED ok@REDACTED
Tue Feb 12 22:33:58 CET 2013


The central fact here is that we have NO evidence that
anyone anywhere has ever been prevented from
"getting things done" by the lack of this "feature".
The last time I checked, over half a dozen different
ways to do what the original poster wanted had been
suggested.

Here's one of the ones I suggested, spelled out in full.
(No prizes awarded for guessing which of Reynolds' papers
inspired it.)

-define(GET(F,X),   (hd(F))(X)).
-define(UPD(F,X,V), (tl(F))(X, V)).
-define(REF(R,F),   [ fun (ZX)     -> ZX#R.F       end
                    | fun (ZX, ZV) -> ZX#R{F = ZV} end]).


?REF(record_name, field_name)
returns a pair of functions, a "get" function and an
"update" function.

?GET(field_pair, record_value)
applies the get function in a field pair to a record
value.

?UPD(field_pair, record_value, new_value_for_field)
applies the update function in a field pair to a
record value and a new value for the field.

So we have
 - a single value
 - that can be passed around, sent in a message, &c
 - that identifies a field
 - and can be used to dynamically select
 - or update that field.
AND
 - by searching for occurrences of ?REF, you can
   discover which fields may be dynamically referenced.

As for readability, just because something is assessed
differently by different people, that does not mean
that there are no comparisons can be made.
There are indeed variations in taste about things like
well_separated or baStudlyCaps or runtogethernames,
about indentation and use of white space, about a
bunch of things.  But _within_ any single style,
requiring someone to perform more mental work to
discover information they need makes it less readable.

At one extreme, you have COBOL, where interesting
facts are lost in a vast forest of verbiage.  At the
other extreme, you have J, where you have to puzzle
over every single character:   avg=: +/ % #
Haskell can be very close to the J end of the spectrum;
Haskell written by masters can require Vetinari-level
puzzle skills to decode.  Erlang is somewhere in the
middle, where the code isn't so bulky that the facts
you need are needles in a haystack, and not so terse
that you don't recognise them when you see them.





More information about the erlang-questions mailing list