Erlang/OTP Forums

Author Message

<  Erlang  ~  programmatic method to build a record

5hundy
Posted: Tue Nov 11, 2008 10:41 pm Reply with quote
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=...}
View user's profile Send private message
rvirding
Posted: Wed Nov 12, 2008 9:31 pm Reply with quote
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.
View user's profile Send private message Visit poster's website MSN Messenger
keymone
Posted: Tue Jan 06, 2009 10:51 am Reply with quote
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.
View user's profile Send private message MSN Messenger ICQ Number

Display posts from previous:  

All times are GMT
Page 1 of 1
This forum is locked: you cannot post, reply to, or edit topics.

Jump to:  

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