Is there an easier way to change the value in the subsubsub record field in Erlang?

So, I have a pretty deep hierarchy of record definitions:

-record(cat,            {name = '_',           attitude = '_',}).
-record(mat,            {color = '_',          fabric = '_'}).
-record(packet,         {cat = '_',            mat = '_'}).
-record(stamped_packet, {packet = '_',         timestamp = '_'}).
-record(enchilada,  {stamped_packet = '_', snarky_comment = ""}).

And now I have an enchilada, and I want to create a new one, just like the meaning of one of the subtasks. Here is what I did.

update_attitude(Ench0, NewState)
  when is_record(Ench0, enchilada)->

    %% Pick the old one apart.
    #enchilada{stamped_packet     = SP0} = Ench0,
    #stamped_packet{packet = PK0} = SP0,
    #packet{cat = Tag0}    = PK0,

    %% Build up the new one.
    Tude1 = Tude0#cat{attitude = NewState},
    PK1 = PK0#packet{cat = Tude1},
    SP1 = SP0#stamped_packet{packet = PK1},

    %% Thank God that over.
    Ench0#enchilada{stamped_packet = SP1}.

Just thinking about it hurts. Is there a better way?

+3
source share
2 answers

As Hynek suggests, you can exclude temporary variables and do:

update_attitude(E = #enchilada{stamped_packet = (P = #packet{cat=C})},
                NewAttitude) ->
    E#enchilada{stamped_packet = P#packet{cat = C#cat{attitude=NewAttitude}}}.

Yariv Sadan was disappointed with the same problem and wrote Recless , a type that outputs parsing for records that allows you to write:

-compile({parse_transform, recless}).

update_attitude(Enchilada = #enchilada{}, Attitude) ->
    Enchilada.stamped_packet.packet.cat.attitude = Attitude.
+4
source

Try the following:

update_attitude(E = #enchilada{
    stamped_packet = (SP = #stamped_packet{
      packet = (P = #packet{
        cat = C
    })})}, NewState) ->
    E#enchilada{
      stamped_packet = SP#stamped_packet{
        packet = P#packet{
          cat = C#cat{
            attitude = NewState
    }}}}.

In any case, structures are not the most powerful part of Erlang.

+1
source

Source: https://habr.com/ru/post/1703958/


All Articles