How do I build a list of elements extracted from a

2019-09-18 05:26发布

I have a list with elements like: {First, Second} Now I want to build a list containing each First element from the first list, how do I do that?

Does this work:

List = [L || {First, Second} = FirstList, L <- First].

标签: list erlang
2条回答
女痞
2楼-- · 2019-09-18 05:58

You want this:

Results = [First || {First, _Second} <- List].

It creates a list of First, where {First, _Second} comes from List.

We're using matching to decompose the tuples. The underscore on _Second denotes that we're not using it (and suppresses the warning to that effect). You could use a plain _, but I often use the longer form to sort-of document what's going on.

The resulting list is made up of all of the First values.

You can play with this stuff in the Erlang shell. To answer the question you posed in your comment:

1> Players = [{a,1},{b,2},{c,3}].
[{a,1},{b,2},{c,3}]
2> OtherPlayers = [{P,Q} || {P,Q} <- Players, Q =/= 3].
[{a,1},{b,2}]

Here, we're setting up the original list (I used atoms for player names, simple integers instead of pids). Then we create a new list of {P,Q} tuples, such that {P,Q} comes from the original list, with a filter that Q =/= 3.

You can read more about list comprehensions (and filters) in the Erlang documentation or in Learn you Some Erlang.

查看更多
贪生不怕死
3楼-- · 2019-09-18 06:08

Try this:

[L || {L,R} <- FirstList].
查看更多
登录 后发表回答