繁体   English   中英

Haskell:类型类:多继承示例

[英]Haskell: type classes: multiple inheritance example

我开始知道我们可以使用类型类实现多重继承。 我写过小的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类型自动实现EqShow ,这意味着他们必须首先实现EqShow才能实现C

class在Haskell是不一样的一class在Java中,或者说,它更接近一个接口,但它不能在相同的方式使用(也不应该)。 Haskell实际上并没有OOP意义上的继承或类的概念,因为它不是OOP语言。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM