Better notation to re-use `&`?
See original GitHub issueCurrently, 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 &
binds $
. 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&+&
would mean($) => $+$
. 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&+&&
or&+&2
or&1+&2
. - Almost the opposite:
&&
or&1
could mean “re-use the last&
variable”, similar to how$
behaves now. We could extend to&&&
or&2
referring to two levels up, etc. - Similar to 2, we could use a special notation for the current
&
argument, like^
, or^^
for two levels up etc. Or&^
,&^^
, etc.
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.
&+$
would become($$) => $$ + $
. If you want($) => $+$
, write that.
Also possibly related to pipe operator and https://github.com/DanielXMoore/Civet/issues/75#issuecomment-1365340146 …
Issue Analytics
- State:
- Created 9 months ago
- Comments:5 (5 by maintainers)
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.