当前位置 : 主页 > 手机开发 > 其它 >

Haskell:类型类:多继承示例

来源:互联网 收集:自由互联 发布时间:2021-06-19
我开始知道我们可以使用类型类实现多重继承.我写过小的 haskell代码,但无法弄清楚问题. {-# LANGUAGE GeneralizedNewtypeDeriving #-}{-# LANGUAGE DeriveAnyClass #-}{-# LANGUAGE StandaloneDeriving #-}class (Eq a, S
我开始知道我们可以使用类型类实现多重继承.我写过小的 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

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

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.

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

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

class (Eq a, Show a) => C a where

并不意味着实现C的类型自动实现Eq和Show,这意味着他们必须首先实现Eq和Show才能实现C.

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

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

网友评论