Isn't it possible to define closure with generic types?

I'm a functional programmer and try to use Rust in a functional way.

I've read

Monads and GATs in nightly Rust

however, it's disappointing to have seen the code is just to implement Object&Method in the OOP paradigm.

Monads and Functors can be defined in a purely functional way, and what's fundamentally required is Higher-order generic typed functions(people prefer to call HKT or something).

I've also read here

Possible to define generic closure?

but this is 6 years ago.

Either way, without Higher-order generic typed function, it's impossible to compose Functor or Monad in the standard functional way.

I'm also surprised I can't define a simple identity function properly in the simple lambda expression form.

let identity = <T>|a:T| a;

It's 2022 now, and is there any workaround?


Solution 1:

Isn't it possible to define closure with generic types?

No, as per 2022 and rust 1.58 it is still not.

As alternatives:

You can define a function in (almost?) any scope, so as a replacement for |a:T| -> T { a }:

fn main() {
    fn id<T>(a: T) -> T {
        a
    }
    for i in 0..10 {
        println!("{}", id(i));    
        println!("{}", id("Foo"));    
    }
}

Playground

You can also redefine lambdas as per needed (although I would still use a function for it):

fn main() {
    for i in 0..10 {
        let id = |a| a;
        println!("{}", id(i));
        let id = |a| a;
        println!("{}", id("Foo"));    
    }
}

Playground