nim-lang / RFCs

A repository for your Nim proposals.
135 stars 26 forks source link

Make (fn)expr syntax behave like a unary operation #415

Open n0bra1n3r opened 2 years ago

n0bra1n3r commented 2 years ago

Current behavior

There is a variant of the Nim command syntax that looks like this:

proc x2(arg: int): int = arg * 2

echo (x2)2

which expands to

echo x2(2)

I use this syntax to call unary "operator-like" procs. However, this does not actually behave like an operator. For example:

echo (x2)2 + 1 # prints 6

Proposed behavior

I propose the following behavior:

echo (x2)2 + 1 # prints 5

The difference is that the current behavior expands the call to x2(2 + 1), and the desired behavior would expand the call to x2(2) + 1 instead.

Future considerations

Perhaps this could be expanded to allow syntax like 2 (x) 2 to expand to x(2, 2), which is similar to Haskell's use of backticks to achieve the same effect.

konsumlamm commented 2 years ago

(x2)2 + 1 evaluating to 5 is consistent with x2 2 + 1 being interpreted as x2(2 + 1). I don't see what the problem with just calling x2(2) + 1 is. This change would just unnecessarily break existing code (sometimes silently), without any real benefit.

n0bra1n3r commented 2 years ago

(x2)2 + 1 evaluating to 5 is consistent with x2 2 + 1 being interpreted as x2(2 + 1)

To me what's inconsistent is the way spacing is ignored here, which is different from the way spaces are treated in other forms of function invocation:

echo `$` 2 + 1 # prints 3
# echo $2 + 1 # error
echo(2, 1) # prints 21
echo (2, 1) # prints (2, 1)

without any real benefit

In terms of real benefit, this is a syntactical proposal, so it's similar to the benefit of the command syntax: why not just use fn(a) instead of fn a for everything? I posted this on the chance that (fn)a is currently a lesser-known construct (evidence TBD), but it is probably too late to implement this if people are using (fn)2 + 1 to mean fn(2 + 1) already.

The "gain" I want from this is to define custom operators that are words (like the built-in addr; or like and if the "future consideration" is added), like Haskell with their 2 `x` 2 syntax.

n0bra1n3r commented 2 years ago

Just adding a reference to my not-so-popular C/C++ interop library here that could take advantage of this feature, for documentation.