| Author |
Message |
< Erlang ~ programmatic method to build a record |
| 5hundy |
Posted: Tue Nov 11, 2008 10:41 pm |
|
|
|
User
Joined: 14 Oct 2007
Posts: 17
|
Is there a way to build a record from, say, a proplist in a way that doesn't require that I know all of the record's fields? For example:
P = [{type, "cow"}, {legs, 4}].
-record(animal, {type, legs}).
How can I create a new animal from the contents of P without doing:
#animal{type=..., legs=...} |
|
|
| Back to top |
|
| rvirding |
Posted: Wed Nov 12, 2008 9:31 pm |
|
|
|
User
Joined: 30 Aug 2006
Posts: 452
Location: Stockholm, Sweden
|
| Unfortunately no, there is no way to do that. You must remember that records are purely compile time constructions. |
|
|
| Back to top |
|
| keymone |
Posted: Tue Jan 06, 2009 10:51 am |
|
|
|
User
Joined: 17 Sep 2007
Posts: 11
Location: Lviv, Ukraine
|
record is just a tuple, in your case: {animal, Type, Legs}
there is record_info/2 function which gives you a list of fields so you can do something like
Code:
build_record(record_name, Props) ->
Fields = record_info(fields, record_name),
build_record(record_name, Props, Fields).
build_record(record_name, Props, Fields) ->
build_record(record_name, Props, Fields, {record_name}).
build_record(record_name, [], [], Record) ->
{ok, Record};
build_record(record_name, Props, [], Record) ->
{error, unknown_properties_in_proplist};
build_record(record_name, [{Field, Value}|Props], [Field|Fields], Record) ->
NewRecord = append_element(Record, Value),
build_record(record_name, Props, Fields, Record);
build_record(record_name, Props, [_|Fields], Record) ->
NewRecord = append_element(Record, undefined),
build_record(record_name, Props, Fields, Record).
but you must know at least record name, you can't pass it in variable
P.S. the above snippet of code has critical bug - if you provide a list of props in incorrect order record won't be created. |
|
|
| Back to top |
|
|
|
All times are GMT
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You cannot download files in this forum
|
|
|