Question

So I was playing with streams in Elixir and I was playing with the |> operator as well; I have a lot of experience playing with F# and so it feels pretty natural. So I tried this:

1..10 |> Stream.map &(&1 * &1) |> Enum.to_list

Just to spit out a list of the first ten squares. But it didn't work. No problem; just seemed to be a problem of operator precedence because this works fine:

(1..10 |> Stream.map &(&1 * &1)) |> Enum.to_list

But I was wondering if this could be rewritten without having to parenthesize the first half of the expression.

Was it helpful?

Solution

I think your problem lies in the fact that you're calling Stream.map without parentheses, and then try to pipe. I must admit, I'm not sure of the mechanics, but your original call seems to be interpreted as:

1..10 |> Stream.map(&(&1 * &1) |> Enum.to_list)

I would rewrite this to use parens in the function call:

1..10 |> Stream.map(&(&1 * &1)) |> Enum.to_list

Personally, I mostly use parens in function calls. The exceptions to this are zero arg function calls, macro calls, and occasional IO.puts/inspect calls (which I usually do just for debugging purposes).

I find this approach to be very helpful, in particular when piping, because it removes possible ambiguities.

OTHER TIPS

I am a beginner too, so kindly point out if I am wrong, but you can do it like this too right ?

iex(11)> 1..10 |> Enum.map(&(&1 * &1))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top