Skip to content

"--" should have explicit parens in the formatter #13710

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
sschuldenzucker opened this issue Jul 7, 2024 · 2 comments · Fixed by #13711
Closed

"--" should have explicit parens in the formatter #13710

sschuldenzucker opened this issue Jul 7, 2024 · 2 comments · Fixed by #13711

Comments

@sschuldenzucker
Copy link

Elixir and Erlang/OTP versions

Erlang/OTP 26 [erts-14.2.5] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit] [dtrace]

Elixir 1.17.0 (compiled with Erlang/OTP 26)

Operating system

MacOS Sonoma 14.5

Current behavior

The "--" operator that 'subtracts' lists from each other has the highly unintuitive property that it's right-associative. Specifically:

iex(1)> [1,2,3,4] -- [1,2] -- [3]
[3, 4]
iex(2)> ([1,2,3,4] -- [1,2]) -- [3]
[4]

Line (1) is parsed as [1,2,3,4] -- ([1,2] -- [3]) = [1,2,3,4] -- [1,2]. This is documented correctly but it seems extremely counter-intuitive: it seems to me that everyone parses line (1) as "take [1,2,3,4], then remove 1 and 2, then remove 3. It's also inconsistent with the behavior of "-" (subtraction for numbers)

Expected behavior

"--" should be left-associative so that the two lines above are equivalent.

@sabiwara
Copy link
Contributor

sabiwara commented Jul 7, 2024

This is mostly due to consistency with ++ (which has to be right-associative for performance reasons) and consistency with erlang which made the same decision (see this thread).

Changing it would be a breaking change so I'm not sure we can go ahead.

I wonder if there are other options to mitigate this and avoid the surprise, such as:

  • warn in such cases and ask to add parentheses to make the intended order explicit
  • have the formatter add parentheses in such cases so x -- y -- z becomes x -- (y -- z) (making it explicit what will happen)

@josevalim
Copy link
Member

Yes, we cannot change the precedence and warning would be complicated. We could make the parens explicit in the formatter though.

@josevalim josevalim changed the title "--" should be left-associative "--" should have explicit parens in the formatter Jul 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging a pull request may close this issue.

3 participants