有人愿意使用Functional Programming和Elixir Constructs为List(X)中的重复值提供一些替代解决方案吗?
X = [1,26,3,40,5,6,6,7] # the 6 being the duplicate
Run Code Online (Sandbox Code Playgroud)
我想到的用于解决此问题的库存解决方案是迭代列表(X),并添加到新的列表(Y),其中密钥尚不存在.
谢谢
Paw*_*rok 45
Enum.uniq 做你想要的,例如:
iex(6)> Enum.uniq([1,26,3,40,5,6,6,7])
[1, 26, 3, 40, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
就你如何实现它而言,你可以编写一个递归函数,如下所示:
defmodule Test do
def uniq(list) do
uniq(list, HashSet.new)
end
defp uniq([x | rest], found) do
if HashSet.member?(found, x) do
uniq(rest, found)
else
[x | uniq(rest, HashSet.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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10695 次 |
| 最近记录: |