[erlang-questions] Dynamically access record fields

Jeremy Ong <>
Sat Feb 9 23:48:37 CET 2013


On Sat, Feb 9, 2013 at 2:33 PM, Dmitry Kolesnikov <>wrote:

> Hello,
>
> I am not precisely sure what you mean by saying "Erlang doesn't seem to
> support this …"
> Record is a syntax sugar for tuples, all operations applicable for tuples
> are also valid for records.
> Keep in-mind that tuple elements are addressable.
>
>
> -module(rec).
>
> -export([test/0]).
>
> -record(foo, {a, b, c}).
>
> test() ->
>    V1 = #foo{a="A", b="B", c="C"},
>    io:format("rec ~p~n",     [V1]),
>    io:format("rec got ~p~n", [element(#foo.a, V1)]),
>    V2 = setelement(#foo.a, V1, "A+"),
>
>    io:format("rec ~p~n",     [V2]),
>    io:format("rec got ~p~n", [element(#foo.b, V2)]),
>    V3 = setelement(#foo.b, V2, "B+"),
>
>    io:format("-> ~p~n",     [V3]).
>
>
>
What I was saying was that you can't do something like

Field = a,
V2 = setelement(#foo.Field, V1, "A+")


>
> - Dmitry
>
>
> On Feb 9, 2013, at 11:40 PM, Jeremy Ong <> wrote:
>
> Hmm, upon reading more, it seems like all record functionality is
> implemented in the compiler pass.
>
> It seems like the ability to address particular variable named locations
> in tuples would be desirable. I guess I'll have to use proplists or a dict
> for now, although it feels like overkill for what I'm doing.
>
>
> On Sat, Feb 9, 2013 at 1:37 PM, Jeremy Ong <> wrote:
>
>> Suppose I have a record that looks like
>>
>> -record(foo, {bucket1, bucket2}).
>>
>> I may want to pass in an argument specifying what bucket to perform the
>> operation over.
>>
>> For example,
>>
>> Bucket = bucket1,
>>
>> then later,
>>
>> Use Foo#foo.Bucket for some operations and also modify Bucket with
>> something like
>>
>> Foo#foo{Bucket = bar}
>>
>> Erlang doesn't seem to support this, and I don't see why not? Is there a
>> better way to go about this?
>>
>> Real World Example,
>>
>> If the record stores data about two people playing a game against one
>> another, and one of them disconnects, I want to perform some operations on
>> the disconnected player's data, and notify the other player that the
>> disconnect occurred. Not having this sort of functionality results in some
>> code duplication and messy code (at least, if using records).
>>
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130209/e36c404c/attachment.html>


More information about the erlang-questions mailing list