Rust does not have higher-kinded-types. For example, functor (and thus monad) cannot be written in Rust. I would like to know if there is a deep reason explaining this and why.<
Time & Priority.
The absence of Higher Kinded Types is not a design decision, per se. It is intended that Rust will have some form of it, with the more popular candidate being Generic Associated Types (2017) at the moment.
Implementing those take time, though, and has not been judged a priority compared to other features. For example, async/await was prioritized over HKTs, and const generics also seem to be prioritized.
For example, functor (and thus monad) cannot be written in Rust.
Actually, they can, although it's a bit unwieldy.
See Edmund's Smith lovely hack which he posted on https://www.reddit.com/r/rust/comments/cajn09/new_method_for_emulating_higherkinded_types_in/:
trait Unplug {
type F; //The representation type of the higher-kinded type
type A; //The parameter type
}
trait Plug {
type result_t;
}
pub struct Concrete,A> {
pub unwrap: >::result_t
}
impl, A> Concrete {
fn of + Plug>(x: MA) -> Self
where M: Plug
{
Concrete { unwrap: x }
}
}
With which they implement a Functor
trait:
pub trait Functor: Unplug + Plug<::A> {
fn map(f: F, s: Self) -> >::result_t
where
Self: Plug,
F: FnMut(::A) -> B
;
}
// Example impl for a represented Vec
impl Functor for Concrete, A> {
// remember, Self ~ (Vec<_>, A) ~ "f a"
fn map(f: F, s: Self) -> >::result_t
where
F: FnMut(::A) -> B
{
Concrete::of(s.unwrap.into_iter().map(f).collect())
}
}
And from then on build Applicative
and Monad
:
pub trait Applicative: Functor {
fn pure(s: ::A) -> Self;
fn app(
f: >::result_t, //M
s: Self //M
) -> >::result_t //M
where
F: FnMut(::A) -> B + Clone,
Self: Plug + Plug + Unplug,
>::result_t:
Unplug::F, A=F> +
Plug +
Clone,
::F: Plug
;
}
pub trait Monad : Applicative {
fn bind(f: F, s: Self) -> >::result_t
where
Self: Plug+Plug,
F: FnMut(::A) ->
>::result_t + Clone
;
}
I did say it was a bit unwieldy...