[erlang-questions] Creating records dynamically
Richard O'Keefe
ok@REDACTED
Fri Jan 22 02:23:26 CET 2010
I'm trying to think of a good use for a function that takes a
record name as an argument and uses it for construction.
I have had good success imagining square circles, but not this.
Amongst other things,
- "unwarranted chumminess" with the compiler's representation of
records
- how come there are lots of record types with the same field names?
- what is supposed to happen if you pass an atom that is NOT the name
of a record, or is the name of a record but not one visible in this
module, or is the name of a record visible in this module that
doesn't
have all those fields
- how would you write a type specification for the put_vals function?
- why not pass a constructor *function* instead of a record name,
so that you aren't crippled by a restriction to constructing
records?
E.g.,
put_vals(F) -> F(1, 2).
... put_vals(fun (X,Y) -> #sample{a = X, b = Y} end) ...
Of course, if you find yourself passing the same constructor function
more than once, you would do well to give it a name:
mk_sample_a_b(A, B) -> #sample{a = A, b = B}.
... put_vals(fun mk_sample_a_b/2) ...
Convention:
mk_<record name>{_<field name>}...
The horrible thing about Yau-Hsien Huang's sample code
-module(test).
-record(sample, {a, b}).
test(T) ->
case put_vals(T) of
#sample{a=X, b=Y} -> [sample, X, Y];
Any -> Any
end.
put_vals(T) ->
{T, 1, 2}.
is that it breaks if the -record declaration is changed,
say to -record(sample, {b, a}). % change order
or -record(sample, {a, b, c}). % change size
BOA constructors have no place in Erlang.
More information about the erlang-questions
mailing list