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

StackOverflow https://stackoverflow.com/questions/23626189

  •  21-07-2023
  •  | 
  •  

Domanda

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].
È stato utile?

Soluzione

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.

Altri suggerimenti

Try this:

[L || {L,R} <- FirstList].
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top