Reputation: 273
I would like to know how can I use lists:filter to get a specific tuple from a list of tuples. My code is :
myFilter(Item,List)->
MyItems = lists:map(fun(X)-> element(2,X) end,List),
lists:filter(fun()-> lists:member(Item,MyItems) end , List).
Example :
myFilter(1,[{atom1,1,"P1"},{atom2,2,"P1"},{atom3,3,"P3"}]) = {atom1,1,"P1"}
Upvotes: 1
Views: 100
Reputation: 222040
lists:keyfind
is meant for exactly this! lists:keyfind(1, 2, List)
will return the first tuple in the list whose 2nd item is 1
, or return false
if it doesn't find any:
1> List = [{atom1,1,"P1"},{atom2,2,"P1"},{atom3,3,"P3"}].
[{atom1,1,"P1"},{atom2,2,"P1"},{atom3,3,"P3"}]
2> lists:keyfind(1, 2, List).
{atom1,1,"P1"}
Upvotes: 4