Elixir如何对列表理解进行排序?

时间:2016-09-27 11:03:45

标签: sorting elixir list-comprehension

我一直在努力将这个列表理解排序一段时间,而且我不明白它的两个具体事项。

for x <- span(2, n), y <- span(2, n), x <= y, x * y <= n, into: [], do: x * y

它的作用是创建一个包含n的所有非素数的列表。现在,如果我尝试:

for x <- span(2, n), y <- span(2, n), x <= y, x * y <= n, into: [], do: x * y
  |> Enum.sort


for x <- span(2, n), y <- span(2, n), x <= y, x * y <= n, into: [], do: x * y   
  |> Enum.sort()

这两种方法都给我错误:

protocol Enumerable not implemented for 4

所以我的第一个问题是你如何使用管道对理解进行排序?

编辑::由于存在重复而被删除,而我没有注意到他们=&gt;

如果我尝试:

comps = for x <- span(2, n), y <- span(2, n), x <= y, x * y <= n, into: [], do: x * y
Enum.sort(comps)

列表已排序,但现在它在列表中显示重复项。   我的第二个问题是,为什么理解的输出包含重复,如果我将它存储在变量中而不包含它们呢?

这似乎是一种相当随意的互动。

1 个答案:

答案 0 :(得分:3)

在进一步阅读时,解决方案是在管道之前包含对括号的理解。

(for x <- span(2, n), y <- span(2, n), x <= y, x * y <= n, into: [], do: x * y)
  |> Enum.sort 

以上代码是解决方案。当以块格式管道理解时,不需要括号,但内联理解需要括号。

我通过阅读Elixir: error when piping to a function the result of inline comprehension

发现了这一点

我在发布之前没有发现这个问题,虽然我搜索了Elixir的理解,因为我不知道“内联理解”一词。