Reputation: 507
Failing code:
Enum.map(1..30, &(&1 * 2)) |> Enum.map &(&1 + 1) |> Enum.sum
** (Protocol.UndefinedError) protocol Enumerable not implemented for 3
(elixir) lib/enum.ex:1: Enumerable.impl_for!/1
(elixir) lib/enum.ex:112: Enumerable.reduce/3
(elixir) lib/enum.ex:1400: Enum.reduce/3
(elixir) lib/enum.ex:1043: anonymous fn/3 in Enum.map/2
(elixir) lib/enum.ex:1387: Enum."-reduce/3-lists^foldl/2-0-"/3
(elixir) lib/enum.ex:1043: Enum.map/2
But this works perfectly fine:
iex(18)> arr = Enum.map(1..30, &(&1 * 2)) |> Enum.map &(&1 + 1)
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43,
45, 47, 49, 51, 53, 55, 57, 59, 61]
iex(19)> arr |> Enum.sum
960
Is there anything wrong in my first implementation?
Upvotes: 0
Views: 1333
Reputation: 84180
If you are running Elixir 1.2 then you should see a warning:
warning: you are piping into a function call without parentheses, which may be ambiguous. Please wrap the function you are piping into in parentheses. For example:
foo 1 |> bar 2 |> baz 3
Should be written as:
foo(1) |> bar(2) |> baz(3)
Change your first example to:
Enum.map(1..30, &(&1 * 2)) |> Enum.map(&(&1 + 1)) |> Enum.sum
See Why Can't I Chain String.replace? for a detailed explanation.
Upvotes: 5