Reputation: 188
Enum.member/2
is only able to check for one elements membership. Like
Enum.member ["abc", "def", "ghi", "123", "hello"], "abc" -> true
Is there a way to use an anonymous function, etc. for checking membership of multiple items, and returning false if one of the elements is not included to stay DRY and avoid something like this?
Enum.member ["abc", "def", "ghi", "123", "hello"], "abc"
Enum.member ["abc", "def", "ghi", "123", "hello"], "def"
Enum.member ["abc", "def", "ghi", "123", "hello"], "ghi"
Upvotes: 5
Views: 2376
Reputation: 54734
Another option would be to work with sets, then check with MapSet.subset?/2
iex(1)> list = ["abc", "def", "ghi", "123", "hello"]
["abc", "def", "ghi", "123", "hello"]
iex(2)> MapSet.subset?(MapSet.new(["abc", "def", "ghi"]), MapSet.new(list))
true
iex(3)> MapSet.subset?(MapSet.new(["abc", "def", "jkl"]), MapSet.new(list))
false
Upvotes: 3
Reputation: 222428
You can use a combination of Enum.all?/2
(if you want all items to be present) or Enum.any?/2
(if you want any one item to be present) + Enum.member?/2
(or the in
operator, which does the same):
iex(1)> list = ["abc", "def", "ghi", "123", "hello"]
["abc", "def", "ghi", "123", "hello"]
iex(2)> Enum.all?(["abc", "def", "ghi"], fn x -> x in list end)
true
iex(3)> Enum.any?(["abc", "def", "ghi"], fn x -> x in list end)
true
iex(4)> Enum.all?(["abc", "z"], fn x -> x in list end)
false
iex(5)> Enum.any?(["abc", "z"], fn x -> x in list end)
true
Upvotes: 9