Haskell:类型类:多继承示例

Har*_*hna 3 inheritance haskell

我开始知道我们可以使用类型类实现多重继承.我写过小的haskell代码,但无法弄清楚问题.

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE StandaloneDeriving #-}

class (Eq a, Show a) => C a where
    getHashCode :: a -> Integer
    getHashCode obj = 123


type Id = Int
type Name = String

data Employee = Employee Id Name deriving C
Run Code Online (Sandbox Code Playgroud)

当我试图加载上面的代码时,我收到以下错误.对此有任何帮助.

 No instance for (Eq Employee)
      arising from the 'deriving' clause of a data type declaration
   Possible fix:
      use a standalone 'deriving instance' declaration,
        so you can specify the instance context yourself
    When deriving the instance for (C Employee)
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

我搜索谷歌一段时间,但无法找到多重继承的好例子.如果您提供一些信息,例如Haskell中的多重继承,将会很有帮助.

参考:https://www.haskell.org/tutorial/classes.html

bhe*_*ilr 8

class (Eq a, Show a) => C a where
Run Code Online (Sandbox Code Playgroud)

并不意味着实现类型C自动执行EqShow,这意味着他们必须首先落实EqShow他们可以执行之前C.

classHaskell中的A 也与classJava中的不同,它更接近于接口,但它不能以相同的方式使用(并且不应该使用).Haskell实际上并没有OOP意义上的继承或类的概念,因为它不是OOP语言.

但是,如果要为类型自动拥有EqShow实例,只需将它们添加到deriving数据类型的子句中即可.