[erlang-questions] Updating elements of a record

Nathaniel Waisbrot nathaniel@REDACTED
Tue Jan 22 21:23:30 CET 2019


On Tue, Jan 22, 2019, at 3:10 PM, Donald Steven wrote:
> I would like to pass a list of some fields of a record to a function to 
> update those fields, leaving the other fields as they were. The list 
> will be different for each function call. For example, one call might 
> want to change fields 1, 2 and 7, another call only field 8, another 
> call fields 3 and 4. Of course, each field will have a unique name. 
> Each call to updateStatus (let's call it) would look like 
> updateStatus(Status, List_of_Fields_to_Update) -> code.
> 
> --------------------------------
> 
> I can't figure put how to do this economically, without a long 
> succession of tests like:
> 
> extract fieldnames from list...
> 
> case field1name of
>  true -> update field1;
>  false -> ok % do nothing
> end,
> 
> repeat for each field...
> 
> 
> --------------------------------
> 
> Any suggestions?


Do you need it to be a record? This sounds like a use-case for maps:

update_fields(Data, []) ->
 Data;
update_fields(Data, [Field|Rest]) ->
 Value = maps:get(Field, Data),
 NewValue = update_value(Value),
 NewData = maps:put(Field, NewValue, Data),
 update_fields(NewData, Rest).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190122/86852c3a/attachment.htm>


More information about the erlang-questions mailing list