Set different operation is right-associative?

@josevalim , could you please provide some context or reasoning behind making the set difference operation (–) right-associative in Elixir? Is this a common way of evaluating expressions in Elixir (i.e., right-to-left)?

When asking what the result of [:a, :b, :c, :d] -- [:c, :d] -- [:b] is, I suspect most of us would immediately guess [:a]. However, the correct answer is actually [:a, :b]. Why?

This is because the -- operation is right-associative(?), meaning the expression: [:a, :b, :c, :d] -- [:c, :d] -- [:b] is the same as [:a, :b, :c, :d] -- ([:c, :d] -- [:b]).

This behavior feels counterintuitive to many of us, especially since we’re accustomed to operations like subtraction 7 - 3 - 2 being left-associative , where: 7 - 3 - 2 is equivalent to (7 - 3) - 2.

Not exactly an explanation, but -- is also right-associative in Erlang.

The only thing more confusing than either associativity would be having to remember to switch back and forth when jumping between Erlang and Elixir code.

2 Likes