简体   繁体   English

类似于 Haskell 的 MultiParamTypeClasses

[英]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.

相关问题 Haskell MultiParamTypeClasses和UndecidableInstances - Haskell MultiParamTypeClasses and UndecidableInstances Haskell中有类似字典的东西吗? - Is there something like dictionary in Haskell? 是否有类似于Haskell的Incanter? - Is there something like Incanter for Haskell? Lisp 是否有类似 Haskell 的 takeWhile function 的东西? - Does Lisp have something like Haskell's takeWhile function? 什么编程语言有类似Haskell的`newtype` - What programming languages have something like Haskell’s `newtype` 是否可以将F#record的标签用作Haskell中的函数或类似的东西? - Is it possible to use F# record's labels as functions like in Haskell, or something similar? 从Scala中的字符串中读取案例类对象(类似于Haskell的“读取”类型类) - Read case class object from string in Scala (something like Haskell's “read” typeclass) Haskell 在 Racket 中有类似 gensym 的东西吗? - Does Haskell have something like gensym in Racket? Haskell中的并行monad地图?像parMapM这样的东西? - A parallel monad map in Haskell? Something like parMapM? Haskell:类似于“do”符号的应用程序`$`运算符? - Haskell: Something like the application `$` operator for “do” notation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM