Home > Back-end >  Something like Haskell's MultiParamTypeClasses
Something like Haskell's MultiParamTypeClasses

Time:10-11

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).

In Haskell there is a pragma for this behaviour:

{-# 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.

CodePudding user response:

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:

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)
    }
}
  • Related