Mixed pattern matching

Suppose I have these two lists: list1 = ["one", "two", "three"] and list2 = ["two", "four", "three"].

What would be an Elixir-way function to achieve the following: each item of list 2 will be compared to list 1 in the following way: if the item with the same index is the same, then output :yes, if not, if the item is at list 1, then output :ok, else, output :no.

So, for the above example, the output shall be: [:ok, :no, :yes]

I would go with this approach. It can probably be optimized, but if your lists are not going to be enormous, I think it’s good enough. I am curious about other implementations, though.

list1 = ["one", "two", "three"]
list2 = ["two", "four", "three"]

Enum.zip_with(list1, list2, fn
  item, item ->
    :yes

  _list1_item, list2_item ->
    if Enum.member?(list1, list2_item) do
      :ok
    else
      :no
    end
end)

EDIT: my implementation assumes both lists are the same length.

3 Likes

This parses as "If the item in list 2 is at list 2, which does not make sense. Can you please clarify? From your example result, I think it means “If the item currently being compared in list1 is in list2”.

Could also use in: list2_item in list1.

1 Like

Yes, you’re right. I am going to update my post.

Corrected. Thanks.