Elixir从两个列表中删除常见元素
问题描述:
我想从列表a中删除列表b中的元素。
执行此代码后,列表a正在打印[1,2,3,4]。
I want to remove the elements found in list b from list a. The list a is printing [1,2,3,4] after execution of this code.
defmodule Test do
def listing do
a = [1,2,3,4]
b = [3,4,5,6]
Enum.each b, fn elemB ->
a = Enum.filter(a, fn(x) -> x != elemB == true end)
#IO.inspect a
end
IO.inspect a
end
end
Test.listing()
答
您不需要外部的 Enum.each
,可以通过枚举 a
并检查每个元素是否是 b
的成员:
You don't need that outer Enum.each
, you can do it with a single filter by enumerating over a
and checking each element to see if it is a member of b
:
Enum.filter(a, fn el -> !Enum.member?(b, el) end)
输出:
[1, 2]
您当前的解决方案似乎试图修改 a
,但是这不起作用,因为Elixir具有功能且该功能不会产生副作用;每个 中的
a
与 a
不同>这是原始列表。
It looks like with your current solution you are trying to modify a
but that won't work because Elixir is functional and the function can't have side effects; the a
inside your each
is not the same as the a
that is the original list.