# orx_closure
An explicit closure with absolute seperation of the captured data from the function.
## Why
It aims to address certain issues observed working with the regular closures through `fn_traits` such as:
* having to box closures without a good reason,
* having to add generic parameters to structs holding closures without a good reason,
* impossibility (hopefully only for now) of returning a reference to the captured data.
## A. Motivation
Some of the mentioned issues and suggested solution with `Closure` type are discussed here.
### A.1. `expected closure, found a different closure`
We all observe this error messages at one point. This is due to the fact that every closure has a unique type. Further, these are compiler generated types which we cannot type out, instead we can type the `Fn` trait that they implement.
This causes problems in higher order functions; or simply when conditionally assigning a function to a variable.
Consider the following issue [https://github.com/rust-lang/rust/issues/87961](https://github.com/rust-lang/rust/issues/87961). The issue suggests to clarify the error message, but also demonstrates how we are not able to write a very simple function.
```rust
fn returns_closure(hmm: bool, y: i32) -> impl Fn(i32) -> i32 {
if hmm {
move |x| x + y
} else {
move |x| x * y // doesn't compile!
}
}
let add_three = returns_closure(true, 3);
assert_eq!(42, add_three(39));
let times_two = returns_closure(false, 2);
assert_eq!(42, times_two(21));
```
The above code won't compile because of the title of this section :)
= note: expected closure `[closure@src\motiv.rs:6:17: 6:25]`
found closure `[closure@src\motiv.rs:8:17: 8:25]`
Because **impl** in return position does not allow generic returns. It allows us to return one concrete type that we cannot type, which is determined by the body of the function rather than the caller.
Let's break the closure to its components:
* The captured data, say `Capture`. Here `Capture = i32`.
* The non-capturing function; i.e., a function pointer `fn` transforming an `In` to an `Out`, with additional access to the `Capture`. We can type it down as `fn(&Capture, In) -> Out`. Here it is `fn(&i32, i32) -> i32`.
*The choice on the `&Capture` is intentional due to `Fn` being absolute favorite among `Fn`, `FnOnce` and `FnMut`. In other words, we want to be able to call the closure many times and we don't want to mutate. If we want to consume, we can simply capture by value; recall that the data and `fn` are separated.*
If we consider the closure as the sum of these two components; or simply as the pair `(Capture, fn(&Capture, In) -> Out)`; it is clear that both if-else branches have the same type `(i32, fn(&i32, i32) -> i32)`, there is no reason to treat them as different types.
This is exactly what the `Closure<Capture, In, Out>` struct does: it separates the captured data from the function pointer. Then, these functions become two different values of the same type, and hence, the following is valid.
```rust
use orx_closure::*;
fn returns_closure(hmm: bool, y: i32) -> Closure<i32, i32, i32> {
if hmm {
Capture(y).fun(|y, x| x + y)
} else {
Capture(y).fun(|y, x| x * y)
}
}
let add_three = returns_closure(true, 3);
assert_eq!(42, add_three.call(39));
let times_two = returns_closure(false, 2);
assert_eq!(42, times_two.call(21
```
Even the following is allowed :)
```rust
fn returns_closure(hmm: bool, y: i32) -> Closure<i32, i32, i32> {
Capture(y).fun(if hmm { |y, x| x + y } else { |y, x| x * y })
}
```
The error message correctly says *no two closures, even if identical, have the same type*. But this is not a limitation for anonymous functions; they actually have the same type even if they are different as long as they don't capture the environment and have the same signature. `fn`s are nice.
The following is a little more realistic example where we are able to nicely define the type of the `Closure`:
```rust
use orx_closure::*;
fn create_closure(slice: &[i32], exclude_evens: bool) -> Closure<&[i32], i32, Option<i32>> {
Capture(slice).fun(if exclude_evens {
|x, lb| x.iter().filter(|&x| x % 2 == 1 && *x > lb).min().cloned()
} else {
|x, lb| x.iter().filter(|&x| *x > lb).min().cloned()
})
}
let numbers: Vec<i32> = vec![1, 2, 3, 4, 5, 6];
let closure = create_closure(&numbers, true);
let fun = closure.as_fn(); // not to call 'call'
assert_eq!(fun(1), Some(3));
assert_eq!(fun(5), None);
```
#### Why not just `Box` it?
It is true that additional indirection solves not all but most of the problems mentioned here. For instance, the following code compiles and works just fine.
```rust
fn returns_closure(hmm: bool, y: i32) -> Box<dyn Fn(i32) -> i32> {
if hmm {
Box::new(move |x| x + y)
} else {
Box::new(move |x| x * y)
}
}
let add_three = returns_closure(true, 3);
assert_eq!(42, add_three(39));
let times_two = returns_closure(false, 2);
assert_eq!(42, times_two(21));
```
The greatest power this brings is the ability to forget about the captured data. It is not in the signature, completely abstracted away. We don't know its size, we don't need to since it's now a trait object. However, it comes with certain drawbacks:
* It adds the indirection. This will lead to additional allocation.
* Furthermore, and maybe more importantly, the possibility for compiler optimizations is significantly lower.
* And a matter of taste; the code becomes noisy with words `dyn`, `Box` and `Box::new` which has to be repeated in every branch.
Also we are sometimes driven by a chain of events with such indirection:
* As mentioned above, we notice we have to use a trait object, so we go with `Box<dyn Fn(i32) -> i32>`.
* As a first class citizen, we pass this function to another function as one of its arguments that is of generic type `F: Fn(i32) -> i32`.
* Everything works fine.
* At some point, we are required to easily and cheaply `Clone` and share the closure. Therefore, we change the indirection to be `Rc<dyn Fn(i32) -> i32>`.
* And suddenly, we cannot pass this closure to the other function since **`Fn<(i32,)>` is not implemented for `Rc<dyn Fn(i32) -> i32>`**.
* Not possible to pass the closure as a point-free value.
* We sadly write another closure which does nothing but call this closure.
* Not a big deal, but makes you ask why.
### A.2. Lifetimes!
It is super easy to get the compiler angry with lifetimes when closures start returning references.
#### Simplest Closure to Return a Reference
... would be the one that returns a reference to the captured value. This might not look particularly useful but it actually is useful to demonstrate the problem.
```rust
let x = 42;
let return_ref_to_capture = move || &x;
// <- won't compile: ^^ returning this value requires that `'1` must outlive `'2`
```
For different reasons, yet with the same error message, the following closure version won't compile either:
```rust
let x = 42;
We did solve the problem to return a reference by using `ClosureRef`. However, we often return `Option<&Out>`. The return type itself is not a reference but has a lifetime related with the lifetime of the closure. Therefore, we need something else. Namely, `ClosureOptRef` which has the function pointer signature of `fn(&Capture, In) -> Option<&Out>`. Once we switch to this signature, everything again works.
```rust
let x = 42;
| `Closure<Capture, In, Out>` | `Capture` | `fn(&Capture, In) -> Out` | `Fn(In) -> Out` |
| `ClosureRef<Capture, In, Out>` | `Capture` | `fn(&Capture, In) -> &Out` | `Fn(In) -> &Out` |
| `ClosureOptRef<Capture, In, Out>` | `Capture` | `fn(&Capture, In) -> Option<&Out>` | `Fn(In) -> Option<&Out>` |
| `ClosureResRef<Capture, In, Out, Error>` | `Capture` | `fn(&Capture, In) -> Result<&Out, Error>` | `Fn(In) -> Result<&Out, Error>` |
It is straightforward to decide which closure variant to use:
* If we capture the data by reference, `Capture(&data)`, we can use `Closure` for any return type.
* If we return a value that does not have a lifetime related to the closure, we can again use `Closure` independent of how we captured the data.
* However, if we capture the data with its ownership, `Capture(data)`, and want to return a value lifetime of which depends on the lifetime of the closure:
* we use `ClosureRef` if we want to return `&Out`,
* we use `ClosureOptRef` if we want to return `Option<&Out>`,
* we use `ClosureResRef` if we want to return `Result<&Out, _>`.
*Hoping we eventually need only `Closure`.*
### A.3. Lifetimes when Captured by Ref
The problems explained in **A.2**, leading us to implement four variants, are only relevant when we capture the data by value. The compiler allows us to represent all the abovementioned cases with the `Closure` signature:
```rust
let x = 42;
assert_eq!(closure_opt_ref.call(()), Some(&42));
* It is sized and easy to store in anywhere as a regular struct.
* It auto-implements `Clone` since all possible capture types implement `Clone`.
* `Precedence` struct does not need any generic parameter.
And the following cons:
* `ClosureOneOf3<C1, C2, C3, In, Out>` is a long type; hopefully, we only type it once.
* `Closure::into_oneof3_var1`, ``Closure::into_oneof3_var2``, etc. are type-safe and explicit functions, but not pretty.
To sum up, once the ugliness is hidden in a small box, `Closure` provides a convenient third option between the two extemes:
* having the closure as a generic parameter allowing monomorphization but adding a generic parameter to the parent, and
* having the closure as a `dyn Fn` trait object adding the indirection but not requiring the generic parameter.
This middle ground fits well with closures having specific functionalities such as the `Precedence`.
## C. Relation with `Fn` trait
Note that `Closure<Capture, In, Out>` has the method `fn call(&self, input: In) -> Out`. Therefore, it could have implemented `Fn(In) -> Out`. But the compiler tells me that *manual implementations of `Fn` are experimental*, and adds the *use of unstable library feature 'fn_traits'* error. Not wanting to be unstable, `Closure` does not implement the `Fn` trait.
Instead, `Closure` and all variants have the `as_fn` method, such as `fn as_fn(&self) -> impl Fn(In) -> Out + '_ `, which gives us the compiler generated closure implementing the `Fn` trait.
## License
This library is licensed under MIT license. See LICENSE for details.