Sappe
Sappe

Reputation: 63

Matching and deleting items in list of tuples

I have a list of tuples, say,

[{x, a, y}, {x, b, y}].

Is there a built-in function (or can I use a combination of BIFs) to delete all tuples matching {x, _, y}, as in match and delete based on the first and third term in the tuples, ignoring the second?

Upvotes: 6

Views: 3736

Answers (1)

Christian
Christian

Reputation: 9486

The lists:filter/1 function matches your need, e.g.

Ls = [{x,a,y}, {a,b,c}],
F = fun ({x,_,y}) -> false ; (_) -> true end,
lists:filter(F, Ls).

You can also use list comprehensions, which is like a combination of lists:map/2 and lists:filter/2.

[L || L <- Ls, F(L)]

If your predicate was the opposite, in that you only wanted those matching {x,_,y} you could write it as following, because the generator will filter out those not matching the pattern.

[L || {x,_,y}=L <- Ls]

Upvotes: 14

Related Questions