Syntax idea: use underscores as rvalues to create an implicit closure

This is something I've been thinking about that would make for some nice syntax. Rust already has one of the better syntaxes for closures out of the languages I've used, but this could make some cases even nicer. I'm also taking inspiration from the chain.jl Julia package. Here's some before and after examples of my idea using Rust's tap.rs:

// Turn a two argument function into a one argument function by fixing an argument
foo().pipe(|it| 2.powi(it));
foo().pipe(2.powi(_));

foo().pipe(|it| it * it);
foo().pipe(_ * _);

Luckily using _ as an rvalue is currently a syntax error in Rust, so we shouldn't be infringing on any currently used syntax space. There are some problems with ambiguity though:

foo().pipe(_ * _);

// Could be interpreted as any of
foo().pipe((|it| it) * (|it| it));
foo().pipe(|it| it * it);
|it| foo().pipe(it * it);

So we'd have to come up with a good rule to disambiguate... thoughts?

A couple of things:

  1. Something like this is best discussed on internals.rust-lang.org

  2. This has been proposed before. The takeaway was 2-fold IIRC:

    • that it is unworkable because it will compose poorly with other language features eg macros

    • The current closure syntax is already either optimal or as close to it as can reasonably be achieved, given other constraints like eg the composition issue in 2a

EDIT: found the link to the discussion

8 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.