在列表中提取 Erlang 元组

Extract Erlang tuples in list

我得到了列表中的元组:

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

我要打印的是:

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

您可以简单地以任何您喜欢的方式遍历列表,并使用模式匹配提取元组:

{ Name, ListOfNames } = X

其中 X 是您列表中的当前项目。然后您可以根据需要打印它们。

您可以尝试使用 lists:foreach/2 或者可以尝试实现您自己的迭代函数并打印出列表项:

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).

自定义函数:

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

列出生成器:

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