gpt4 book ai didi

haskell - 类似于 Haskell 的 MultiParamTypeClasses

转载 作者:行者123 更新时间:2023-12-04 18:11:08 26 4
gpt4 key购买 nike

在 Haskell 编程后,我即将开始学习 Rust。trait关键字让我感兴趣,但我注意到您只能引用一种类型( Self )。
在 Haskell 中,这种行为有一个编译指示:

{-# LANGUAGE MultiParamTypeClasses #-}

class ExampleBehaviour a b where
combine :: a -> a -> b
co_combine :: b -> b -> a
但是我看不到在 Rust 中有机地实现这种行为的方法。

最佳答案

我想这就是你要找的:

trait ExampleBehaviour<Other> {
fn combine(x: Other, y: Other) -> Self;
fn co_combine(x: Self, y: Self) -> Other;
}
这是该类型类的 Haskell 实例和相应的特征的 Rust 实现的示例:
data Foo = Foo Int Int
newtype Bar = Bar Int

instance ExampleBehaviour Foo Bar where
combine (Foo x1 y1) (Foo x2 y2) = Bar (x1 * x2 + y1 * y2)
co_combine (Bar x) (Bar y) = Foo x y
struct Foo(i32, i32);
struct Bar(i32);

impl ExampleBehaviour<Foo> for Bar {
fn combine(Foo(x1, y1): Foo, Foo(x2, y2): Foo) -> Self {
Bar(x1 * x2 + y1 * y2)
}
fn co_combine(Bar(x): Self, Bar(y): Self) -> Foo {
Foo(x, y)
}
}

关于haskell - 类似于 Haskell 的 MultiParamTypeClasses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69507728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com