[erlang-questions] Updating elements of a record

Raimo Niskanen raimo+erlang-questions@REDACTED
Wed Jan 23 17:07:58 CET 2019


On Tue, Jan 22, 2019 at 06:04:13PM -0500, Donald Steven wrote:
> I should have said:
> 
> test(Rec, [{a, Val},{c, Val}])
> 
> On 1/22/2019 5.48 PM, Donald Steven wrote:
> > 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.

setelement/3 does exactly that; copies the other fields

> >
> > 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
> >
> 
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list