Sajith Dilshan Jamal
Sajith Dilshan Jamal

Reputation: 331

What does this line of erlang code do?

Could someone explain to me what this line of erlang code does?

[ReportBody|_] = [Body || {<<"val1">>,<<"val2">>,_,_,Body} <- Parts].

You can assume the Parts variable to contain the following:

[{<<"val1">>,<<"val2">>,
         [{<<"val3">>,
           <<"val4">>},
          {<<"val5">>,<<"val6">>},
          {<<"val7">>,<<"val8">>}],
         [{<<"val9">>,
           [{<<"val10">>,<<"val11">>},{<<"val12">>,<<"val13">>}]},
          {<<"val14">>,<<"val15">>},
          {<<"val16">>,[]}],
         <<"val17">>}]

I assume the point of the line of code is to validate if 'val1' and 'val2' exist in 'Parts' and return 'Body'

but is my assumption correct and I would like a detailed explanation of how that line of code works. I am an erlang noob so be gentle.

Upvotes: 0

Views: 91

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170713

It is a list comprehension. It

  1. requires that Parts is a list

  2. for every element of this list, checks if it's a five-element tuple where first element is the binary <<"val1">> and the second element is <<"val2">>.

    1. If yes, the fifth element is called Body and added to the result list.

    2. If no, this element is skipped.

  3. The list consisting of all Body is returned.

  4. (Pointed out in comment) [ReportBody|_] = ... part binds ReportBody to the first element of the list created at 3, dropping the rest.

Upvotes: 3

Related Questions