Reputation: 607
I have been struggling with sorting this list comprehension for a while now, and I don't understand two specific things about it.
for x <- span(2, n), y <- span(2, n), x <= y, x * y <= n, into: [], do: x * y
What it does is create a list of all non-primes up to n. Now if I try:
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()
Both methods give me the error:
protocol Enumerable not implemented for 4
So my first question is how do you sort a comprehension using pipes?
EDIT:: Removed due to duplicates being present and my not noticing them =>
If I try:
comps = for x <- span(2, n), y <- span(2, n), x <= y, x * y <= n, into: [], do: x * y
Enum.sort(comps)
The list is sorted, but now it shows duplicates in the list. My second question is why does the output of the comprehension contain duplicates if I store it in a variable and not contain them otherwise?
That seems like a rather arbitrary interaction.
Upvotes: 2
Views: 745
Reputation: 607
Upon further reading, the solution is to encompass the comprehension in parentheses before piping.
(for x <- span(2, n), y <- span(2, n), x <= y, x * y <= n, into: [], do: x * y)
|> Enum.sort
The above code is the solution. Parentheses are not needed when piping comprehensions in block format, but inline comprehensions require parentheses.
I discovered this by reading: Elixir: error when piping to a function the result of inline comprehension
I did not discover this question prior to my posting although I searched Elixir comprehension, as I was not aware of the term 'inline comprehension'.
Upvotes: 4