rust 没有更高级的种类.例如,函子(以及单子)不能用 rust 迹书写.我想知道是否有一个深刻的原因来解释这一点,为什么.

例如,我能理解的原因可能是,不存在使HKT成为可能的零成本抽象.或者类型推断要困难得多.当然,我也在寻找一个真正的局限性.

如果anwer已经在其他地方提供了,你能给我链接吗?

推荐答案

Time & Priority

从本质上来说,缺少更高级的类型并不是一个设计决定.这是为了让Rust有某种形式,目前更受欢迎的候选人是Generic Associated Types (2017)人.

不过,实现这些功能需要时间,而且与其他功能相比,还没有被视为优先事项.例如,async/await优先于HKTs,而const泛型似乎也优先于HKTs.


例如,函子(以及单子)不能用Rust编写.

事实上,他们可以,尽管这是一个bit的笨拙.

参见他在https://www.reddit.com/r/rust/comments/cajn09/new_method_for_emulating_higherkinded_types_in/上发布的Edmund's Smith lovely hack:

trait Unplug {
    type F; //The representation type of the higher-kinded type
    type A; //The parameter type
}

trait Plug<A> {
    type result_t;
}

pub  struct  Concrete<M: Unplug + Plug<A>,A> {
    pub unwrap: <M as Plug<A>>::result_t
}

impl<M: Unplug + Plug<A>, A> Concrete<M,A> {
    fn of<MA: Unplug<F=M, A=A> + Plug<A>>(x: MA) -> Self
        where M: Plug<A, result_t = MA>
    {
        Concrete { unwrap: x }
    }
}

他们实现了Functor个特征:

pub trait Functor: Unplug + Plug<<Self as Unplug>::A> {
    fn map<B, F>(f: F, s: Self) -> <Self as Plug<B>>::result_t
        where
            Self: Plug<B>,
            F: FnMut(<Self as Unplug>::A) -> B
        ;
}

//  Example impl for a represented Vec
impl<A> Functor for Concrete<Vec<forall_t>, A> {
    //  remember, Self ~ (Vec<_>, A) ~ "f a"
    fn map<B, F>(f: F, s: Self) -> <Self as Plug<B>>::result_t
        where
            F: FnMut(<Self as Unplug>::A) -> B 
    {        
        Concrete::of(s.unwrap.into_iter().map(f).collect())
    }
}

从那时起,建造ApplicativeMonad:

pub trait Applicative: Functor {
    fn pure(s: <Self as Unplug>::A) -> Self;

    fn app<B, F>(
        f: <Self as Plug<F>>::result_t, //M<F>
        s: Self                         //M<A>
    ) -> <Self as Plug<B>>::result_t   //M<B>
    where
        F: FnMut(<Self as Unplug>::A) -> B + Clone,
        Self: Plug<F> + Plug<B> + Unplug,
        <Self as Plug<F>>::result_t:
            Unplug<F=<Self as Unplug>::F, A=F> +
            Plug<F> +
            Clone,
        <Self as Unplug>::F: Plug<F>
    ;
}

pub trait Monad : Applicative {
    fn bind<F,B>(f: F, s: Self) -> <Self as Plug<B>>::result_t
    where
        Self: Plug<F>+Plug<B>,
        F: FnMut(<Self as Unplug>::A) ->
            <Self as Plug<B>>::result_t + Clone
        ;
}

I did say it was a bit unwieldy...

Rust相关问答推荐

重新导出proc宏导致未解决的extern crate错误""

将此字符串转换为由空格字符分隔的空格

当一个箱子有自己的依赖关系时,两个人如何克服S每箱1库+n箱的限制?

为什么允许我们将可变引用转换为不可变引用?

如何计算迭代器适配器链中过滤的元素的数量

如何将映射反序列化为具有与键匹配的字段的定制 struct 的向量?

为什么这个变量不需要是可变的?

用于判断整数块是否连续的SIMD算法.

如何重命名 clap_derive 中的子命令占位符?

.在 Rust 模块标识符中

为什么编译器看不到这个 `From` impl?

.to_owned()、.clone() 和取消引用 (*) 之间有区别吗?

将引用移动到线程中

Rust编译器通过哪些规则来确保锁被释放?

decltype、dyn、impl traits,重构时如何声明函数的返回类型

Rust 中 Mutex<> 的深拷贝?

特征中定义的类型与一般定义的类型之间的区别

RAII 模式的 Rust 解决方案,用于在 new() 和 drop() 上修改另一个对象

在 Rust 中返回对枚举变体的引用是个好主意吗?

当用作函数参数时,不强制执行与绑定的关联类型