- Feature Name:
closure_primitive
- Start Date: 2023-12-23
Summary
This is a way to allow closures to be primitives rather than traits. At some point this may be the default method, and the traits could be deprecated.
Motivation
This is to be done to allow for things that the trait system does not allow, as well as for greater readability and usability. For expample, the trait system does not allow something like nested impl
traits, so something like:
impl Fn(impl Fn(T) -> T)
would not be allowed.
Guide-level explanation
In order to enable this feature, you will use:
#[feature(closure_primitive)]
This type can be used as (<parameters type a>, <parameter type b> -> <return type>)
. This is different then say:
impl Fn(<parameter type a>, <parameter type b>) -> <return type>
So a function that takes a string and returns a function that takes a function and manipulates the prior string would act like this:
fn manipulate(s: &str) -> ((&str -> &str) -> &str) {
|f| {
f(s)
}
}
While this specific use-case is rare, there are many examples where people want to nest closures (in fact, that's how they're most commonly used, so people can nest closures within normal functions.
Reference-level explanation
Ths will be implemented similarly to how closures are implemented currently, simply with the syntax shown shown here, and without the trait system.
Drawbacks
If we deprecate closures-as-traits, this could create issues with backwards compatibility, but if we don't, and they remain used, this could mean that we have to support two systems infinitely.
Prior art
In many functional languages such as Haskell and Futhark, anonymous functions are not structures, traits, or the such, but primitive types.
Unresolved questions
None currently.