类似于 Haskell 的 MultiParamTypeClasses

6 paradigms haskell typeclass type-traits rust

在 Haskell 编程之后,我即将开始学习 Rust。我对关键字trait感兴趣,但我注意到您只能引用一种类型(Self)。

在 Haskell 中有一个针对这种行为的编译指示:

{-# LANGUAGE MultiParamTypeClasses #-}

class ExampleBehaviour a b where
 combine :: a -> a -> b
 co_combine :: b -> b -> a
Run Code Online (Sandbox Code Playgroud)

然而,我看不到在 Rust 中有机地实现这种行为的方法。

Jos*_*ica 7

我认为这就是您正在寻找的:

trait ExampleBehaviour<Other> {
    fn combine(x: Other, y: Other) -> Self;
    fn co_combine(x: Self, y: Self) -> Other;
}
Run Code Online (Sandbox Code Playgroud)

下面是该类型类的 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
Run Code Online (Sandbox Code Playgroud)
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)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Vye我认为这实际上相当于省略 *last* 类型类参数,但是是的,这就是基本思想。 (3认同)