iex(71)> (["a", "b"] -- ["a"]) ++ ["a"]
["b", "a"]
iex(72)> ["a", "b"] -- ["a"] ++ ["a"]
["b"]
Hi team,
Why having the () makes the difference?
Is there a term for this behavior?
Thanks!
iex(71)> (["a", "b"] -- ["a"]) ++ ["a"]
["b", "a"]
iex(72)> ["a", "b"] -- ["a"] ++ ["a"]
["b"]
Hi team,
Why having the () makes the difference?
Is there a term for this behavior?
Thanks!
This is called operator precedence and associativity. You can take a look at the precedence table in the documentation.
The precedence of both operators (--
and ++
) is the same, so they wil be applied in order of their associativity which is “right to left”.
So a -- b ++ c
is equivalent to a -- (b ++ c)
.
Thanks! That makes sense now! Do you know why – and ++ are being applied from right to left instead of left to right?
Operator precedence is defined at: https://hexdocs.pm/elixir/master/operators.html
Thanks fmcgeough. I do see the table. I guess my question is what’s the reason behind having the associativity for ++ and – to be right to left instead of left to right.
ah. gotcha. Its a good question. I know the Erlang precedence is the same. But as for why… sorry. I’m not sure why that choice was made.
I see. It makes sense that elixir gets it from Erlang. Thanks!