If I have two lists:
First list => [1,2,3]
Second List => [3,4,5]
I want this to return true because they both contain 3? If 3 was replaced by 6 it would return false because no elements would match.
Current Attempt
Enum.member?(first_list, fn(x) -> x == second_list end)
Run Code Online (Sandbox Code Playgroud)
Ecto queries:
user_teams = from(
t in MyApp.Team,
left_join: a in assoc(t, :accounts),
where: p.owner_id == ^user.id or (a.user_id == ^user.id and t.id == a.project_id)
) |> Repo.all
current_user_teams = from(
t in MyApp.Team,
left_join: a in assoc(t, :accounts),
where: t.owner_id == ^current_user.id or (a.user_id == ^current_user.id and p.id == a.project_id)
) |> Repo.all
Run Code Online (Sandbox Code Playgroud)
Current Fix:
Enum.any?(user_projects, fn(p) -> p in current_user_projects end)
Run Code Online (Sandbox Code Playgroud)
如果列表很大,那么您可以使用MapSet检查这些列表是否不相交:
iex(1)> xs = [1, 2, 3]
[1, 2, 3]
iex(2)> ys = [3, 4, 5]
[3, 4, 5]
iex(3)> not MapSet.disjoint?(MapSet.new(xs), MapSet.new(ys))
true
Run Code Online (Sandbox Code Playgroud)
如果你想知道什么是交集(两个集合中共有的元素),那么你可以使用:
iex(1)> xs = [1, 2, 3]
[1, 2, 3]
iex(2)> ys = [3, 4, 5]
[3, 4, 5]
iex(3)> MapSet.intersect(MapSet.new(xs), MapSet.new(ys))
#MapSet<[3]>
Run Code Online (Sandbox Code Playgroud)
Use Enum.any?/2 with the in operator (which is just a shorter form of calling Enum.member?/2):
iex(1)> xs = [1, 2, 3]
[1, 2, 3]
iex(2)> ys = [3, 4, 5]
[3, 4, 5]
iex(3)> Enum.any?(xs, fn x -> x in ys end)
true
Run Code Online (Sandbox Code Playgroud)