[英]Something like Haskell's MultiParamTypeClasses
I am about to start learning Rust after programming in Haskell. The trait
Keyword interested me however I noticed you can only refer to one type ( Self
).在 Haskell 编程之后,我即将开始学习 Rust。 trait
关键字让我感兴趣,但是我注意到你只能引用一种类型( Self
)。
In Haskell there is a pragma for this behaviour:在 Haskell 中有一个针对此行为的编译指示:
{-# LANGUAGE MultiParamTypeClasses #-}
class ExampleBehaviour a b where
combine :: a -> a -> b
co_combine :: b -> b -> a
However I cannot see a way to achive this behaviour organically in Rust.但是,我看不到在 Rust 中有机地实现此行为的方法。
I think this is what you're looking for:我想这就是你要找的:
trait ExampleBehaviour<Other> {
fn combine(x: Other, y: Other) -> Self;
fn co_combine(x: Self, y: Self) -> Other;
}
And here's an example of a Haskell instance of that typeclass and a corresponding Rust implementation of the trait:下面是该类型类的 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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.