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"
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With