[erlang-questions] Updating elements of a record

Donald Steven t6sn7gt@REDACTED
Tue Jan 22 23:48:46 CET 2019


Thanks Roger.  I see how this works, but the issue is as much how to get 
it to do:

test([{a, Val},{c, Val}]), leaving, for example, field b untouched.

On 1/22/2019 3.57 PM, Roger Lipscombe wrote:
> 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.
>>
> Records are just tuples. Use setelement with #rec.field:
>
> -module(rec).
> -export([new/0, update/3, test/0]).
>
> -record(rec, {a, b, c}).
>
> new() ->
>      #rec{}.
>
> update(R, Val, [F | Fields]) ->
>      R2 = setelement(F, R, Val),
>      update(R2, Val, Fields);
> update(R, _Val, []) ->
>      R.
>
> test() ->
>      R = rec:new(),
>      R2 = rec:update(R, 2, [#rec.a, #rec.c]),
>      R3 = rec:update(R2, 1, [#rec.b]),
>      R3.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list