rablentain
rablentain

Reputation: 6745

How do I build a list of elements extracted from a list of tuples in Erlang?

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

Upvotes: 0

Views: 182

Answers (2)

Roger Lipscombe
Roger Lipscombe

Reputation: 91925

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.

Upvotes: 4

Ankur
Ankur

Reputation: 33657

Try this:

[L || {L,R} <- FirstList].

Upvotes: 0

Related Questions