Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir Enum member? for multiple elements

Tags:

enums

elixir

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"
like image 744
Sam Shih Avatar asked Jan 03 '23 20:01

Sam Shih


2 Answers

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
like image 63
Dogbert Avatar answered Feb 24 '23 12:02

Dogbert


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
like image 29
Patrick Oscity Avatar answered Feb 24 '23 12:02

Patrick Oscity