[erlang-questions] record type as variable

ok <>
Thu Aug 5 04:44:58 CEST 2010


> On Wed, Aug 4, 2010 at 12:05 PM, Noel Bush <> wrote:
>> Is there any way to specify the type of a record using a variable? I
>> want to be able to do this sort of thing:
>>
>> create(Type, Name) ->
>>    #Type{name = Name}.

I'm trying to think of a use case for this.
When does it make sense to say "I want to make a record;
I'm trusting someone else to tell me what kind, and they
are trusting me to provide all the field values it needs
and all of them with the right types, and I am trusting
them to only sak for 'name' as a required field and
Name as the right type, and we are all
and I'm trusting them to give me something that only ne
is a record name, but I don't know which one, and it's all
very vague really but I'm sure it's going to work..."
You can't do this in any conventional language with records
that I know.  You *can* do (someClass newNamed: aName) in
Smalltalk, but it then #newNamed: is active code that can
do all the validation it wants, not a totally passive
record constructor.

Since there can be a limited number of records in scope in
any one file, what stops you writing

make_named(r1, N) -> #r1{name = N};
...
make_named(rk, N) -> #rk{name = N}.

Now you have something you can attach documentation to,
can type check, can add extra validation code to, and can
limit much more precisely than "any visible record type with
a name field and no other required fields"

You have to write one more line of code for each -record
declaration, but considering the size of the typical
-record declaration this is negligible.
>> record type, that any record type has a name field, etc.) It doesn't
>> seem like that much of a pain to write a few record-handling functions
>> that would allow me to do this,

It's not so much that "it's not much of a pain" to write
suitable functions, it's that it's a whole LOT of a GAIN
to do so.




More information about the erlang-questions mailing list