Better notation to re-use `&`?See original GitHub issue
Currently, if you want a quick function that uses the input twice, e.g.
($) => $+$, you can write
&+$. I find this syntactically inappropriate, as
$ doesn’t appear until you use it the second time; I don’t find it at all intuitive that
$. And it’s especially bad if you use
$ yourself or nest
& functions inside of each other.
I would rather find a notation that is similar in the first and second uses, or that doesn’t use an existing identifier. Obviously
&+& has a meaning though, namely,
($) => $ + ($$) => $$. And it could get more ambiguous with e.g.
Some possible proposals (which I think I mentioned previously in Discord):
- A second
&refers to the same variable as the first, so
($) => $+$. This would forbid nesting a
&function shorthand inside another one, but we can use alternatives to just
&. For example, if you want the current meaning of
&+&, you could use something like
- Almost the opposite:
&1could mean “re-use the last
&variable”, similar to how
$behaves now. We could extend to
&2referring to two levels up, etc.
- Similar to 2, we could use a special notation for the current
^^for two levels up etc. Or
It occurs to me that
&& is probably syntactically ambiguous with the
and operator, so the above suggestions are only really serious with the
&n notation for an integer
n, or something else like
FWIW, Ruby, Crystal, and Elm don’t seem to have anything for this. So another option (other than leaving things as is) would be:
- Forbid accessing the argument a second time.
($$) => $$ + $. If you want
($) => $+$, write that.
Also possibly related to pipe operator and https://github.com/DanielXMoore/Civet/issues/75#issuecomment-1365340146 …
- Created 9 months ago
- Comments:5 (5 by maintainers)
Top GitHub Comments
I think forbidding access to the function variable is probably correct. It just sort of happens to work by chance of implementation currently.
I think in cases where you need to reference the parameter using an explicit arrow function is the simplest and most direct way to do it.
Huh, I was wondering about wrapping
& expressions (or some other notation) in braces to indicate where the function wrapper goes (especially for placeholders). But yeah, not much more concise than an arrow function. I guess the nice thing is not having to spend time naming the arguments and not having to repeat them more than once… So I think it still might be interesting to think about.