grace
grace

Reputation: 25

Extract Erlang tuples in list

I got the tuples in the list:

Contents = [{john, [jill,joe,bob]},
            {jill, [bob,joe,bob]},
            {sue, [jill,jill,jill,bob,jill]},
            {bob, [john]},
            {joe, [sue]}],

The print I want to get is:

john: [jill,joe,bob]
jill: [bob,joe,bob]
sue: [jill,jill,jill,bob,jill]
bob: [john]
joe: [sue]

Upvotes: 1

Views: 87

Answers (2)

vkatsuba
vkatsuba

Reputation: 1449

You can try use lists:foreach/2 or can try implement your own function for iteration and print out lists items:

1> Contents = [{john, [jill,joe,bob]},
{jill, [bob,joe,bob]},
{sue, [jill,jill,jill,bob,jill]},
{bob, [john]},
{joe, [sue]}].
2> lists:foreach(fun({K, V}) -> 
  io:format("~p : ~p~n", [K, V]) 
end, Contents).

Custom function:

% call: print_content(Contents).
print_content([]) ->
  ok;
print_content([{K, V}|T]) ->
  io:format("~p : ~p~n", [K, V]),
  print_content(T).

Lists generators:

1> [io:format("~p : ~p~n", [K, V]) ||  {K, V} <- Contents].

Upvotes: 3

Oliver Mason
Oliver Mason

Reputation: 2270

You can simply iterate over the list in whatever way you like, and extract the tuples with pattern matching:

{ Name, ListOfNames } = X

where X is the current item from your list. Then you can print them as desired.

Upvotes: 0

Related Questions