[erlang-questions] Updating elements of a record

Roger Lipscombe roger@REDACTED
Tue Jan 22 21:57:03 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.
>

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.



More information about the erlang-questions mailing list