shortcut syntax for partial function application
See original GitHub issueCurrently, it’s easy enough, but kinda verbose, to partially apply a function:
value formatHex = (Integer n) => Integer.format(n, 16);
The discussion in #6615 raised the possibility of having a shortcut syntax for the special but very common case where we’re partially applying a function of multiple parameters and obtaining a function with exactly one parameter.
Basic proposal
The proposed syntax would be, approximately:
value formatHex = Integer.format(it, 16);
Where it
is a “magic identifier” or “soft” keyword. (That is, if there is nothing named it
declared in the current scope, it would be given this special interpretation. Furthermore, a warning would be produced wherever the name it
is declared.)
A reasonable objection to this proposal is that it is much too much of a special case:
- it doesn’t handle arbitrary expressions, and
- it only handles the limited case of exactly one argument.
I think these objections are reasonably dispatched by noting that:
- Any attempt to make this work for arbitrary expressions runs into the problem of nesting, as discussed in #7190.
- The single-argument case is, I believe, overwhelmingly the most common case, especially in the context of pipelining discussed in #6615.
Possible extension
An open question is whether this feature could be extended to the receiving instance of a method invocation, in contexts where the receiving instance type can be inferred, for example:
strings.map(it.initial(3));
would mean:
strings.map((s) => s.initial(3))
and:
string |> it.initial(3)) |> list.add
would mean:
string |> ((s) => s.initial(3)) |> list.add
I’m not sure about that, but it’s worth considering.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:13 (10 by maintainers)
Top GitHub Comments
For the record, I dislike the keyword
it
, since I use it for iterators 😃After seeing the version with soft keyword ‘it’, I tend to agree to a degree with @jensli here that the keyword ‘it’ does not really bring out the fact that we are dealing with a partial application here.
If we stay with keyword approach, I would much prefer it if ‘value’ could be used - along with the keyword like treatment in the rest of the language it is much less likely that it would be confused with a local variable name than ‘it’.
Other than that I do have a preference for using ‘_’ (underscore) as a partial application wildcard. I’ve always seen it as a meaningless sigil to replace some variable name whenever I mean to say “I don’t care what is the input; Just do this”