Elixir 从列表中删除重复项
Elixir Remove Duplicates From List
有人愿意提供一些替代解决方案来使用函数式编程和 Elixir 构造从列表 (X) 中删除重复值吗?
X = [1,26,3,40,5,6,6,7] # the 6 being the duplicate
在我看来,解决此问题的常用解决方案是迭代列表 (X),然后添加到键尚不存在的新列表 (Y)。
谢谢
Enum.uniq
做你想做的,例如:
iex(6)> Enum.uniq([1,26,3,40,5,6,6,7])
[1, 26, 3, 40, 5, 6, 7]
就如何实现它而言,您可以编写如下递归函数:
defmodule Test do
def uniq(list) do
uniq(list, MapSet.new)
end
defp uniq([x | rest], found) do
if MapSet.member?(found, x) do
uniq(rest, found)
else
[x | uniq(rest, MapSet.put(found, x))]
end
end
defp uniq([], _) do
[]
end
end
iex(3)> Test.uniq([1, 1, 2, 3, 4, 4, 1])
[1, 2, 3, 4]
另一种可能的解决方案是在创建集合时使用 Set:
[1, 1, 2, 3, 4, 2, 1] |> Enum.into(HashSet.new) #HashSet<[2, 3, 4, 1]>
也使用 MapSet
"3 3 2 1 1" |> String.split |> MapSet.new |> Enum.to_list
==>
[“1”、“2”、“3”]
有人愿意提供一些替代解决方案来使用函数式编程和 Elixir 构造从列表 (X) 中删除重复值吗?
X = [1,26,3,40,5,6,6,7] # the 6 being the duplicate
在我看来,解决此问题的常用解决方案是迭代列表 (X),然后添加到键尚不存在的新列表 (Y)。
谢谢
Enum.uniq
做你想做的,例如:
iex(6)> Enum.uniq([1,26,3,40,5,6,6,7])
[1, 26, 3, 40, 5, 6, 7]
就如何实现它而言,您可以编写如下递归函数:
defmodule Test do
def uniq(list) do
uniq(list, MapSet.new)
end
defp uniq([x | rest], found) do
if MapSet.member?(found, x) do
uniq(rest, found)
else
[x | uniq(rest, MapSet.put(found, x))]
end
end
defp uniq([], _) do
[]
end
end
iex(3)> Test.uniq([1, 1, 2, 3, 4, 4, 1])
[1, 2, 3, 4]
另一种可能的解决方案是在创建集合时使用 Set:
[1, 1, 2, 3, 4, 2, 1] |> Enum.into(HashSet.new) #HashSet<[2, 3, 4, 1]>
也使用 MapSet
"3 3 2 1 1" |> String.split |> MapSet.new |> Enum.to_list
==> [“1”、“2”、“3”]