Elixir从两个列表中删除常见元素 [英] Elixir remove common elements from two lists

查看:68
本文介绍了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.

这篇关于Elixir从两个列表中删除常见元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆