[erlang-questions] Dynamically access record fields

ok <>
Mon Feb 11 01:26:56 CET 2013


> On 9 February 2013 23:57, Dmitry Kolesnikov <>
> wrote:

> Well yes there is.
> What I think Jeremy wants is to dynamically concatenate record names,

No, that's what he's been asking about, but there is some
useful work he is trying to do, and he needs a way to do that
which is, if possible, good performance and good engineering.

So far, we have
 - write accessor functions that provide precisely the access
   needed (fast, safe, maintainable)
 - use dictionaries (slow, dangerous, difficult to maintain)
 - pass funs (medium fast, safe, maintainable)
 - pass indices (fast, dangerous, medium maintainable)
amongst other possibilities.


> Isn't it a drawback?

Isn't the inability to compute field names a drawback?
No.

Is it even good Erlang practice?

Would computing field names be good practice if doable?
No.
>
> I don't want to troll. Is there an EEP about setting record names
> dynamically?

The EEPS site can be read by anybody.
Go over to www.erlang.org/eeps/
and look.

I don't see one, and I can promise you that there will never be
one from my keyboard.  I _have_ proposed frames, which _would_
allow dynamic field names:

    frame_has(Frame, Key) -> true | false
    frame_value(Frame, Key) -> term() | an error exit

Hmm.  I forgot to include setframe_value(Frame, Key, New_Value);
the effect is achievable via
    list_to_frame([{Key,New_Value}|frame_to_list(Frame)])
but it could be implemented rather faster.

It's worth bearing in mind that updating records is expensive.
Each update builds a whole new record.  By looking at the BEAM
code generated for

bar(Old) ->
    Mid = Old#foo{bar=1},
    ugh(Old),
    New = Mid#foo{ugh=2},
    ugh(New),
    New.

you will see that the compiler isn't very smart:  Mid has
only one use, so the definitions of Mid and New could be
fused into a single update, but they are not.  (The test
that Old is a foo cannot move, but the allocation and
rebinding steps could have moved.)

To do anything that would make it easier to update a single
field would be to encourage inefficient programming.





More information about the erlang-questions mailing list