简体   繁体   English

Haskell:类型类:多继承示例

[英]Haskell: type classes: multiple inheritance example

I came to know that we can achieve multiple inheritance using type classes. 我开始知道我们可以使用类型类实现多重继承。 I had written small haskell code, but unable to figure out the problem. 我写过小的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

When i tried to load above code, I am getting following error. 当我试图加载上面的代码时,我收到以下错误。 Any help on this. 对此有任何帮助。

 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.

I searched google some time, but unable to found good example for multiple inheritance. 我搜索谷歌一段时间,但无法找到多重继承的好例子。 it will be helpful if you provide some info, example on multiple inheritance in Haskell. 如果您提供一些信息,例如Haskell中的多重继承,将会很有帮助。

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

Saying

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

does not mean that types that implement C automatically implement Eq and Show , it means that they must first implement Eq and Show before they can implement C . 并不意味着实现C类型自动实现EqShow ,这意味着他们必须首先实现EqShow才能实现C

A class in Haskell is not the same as a class in Java, either, it's closer to an interface, but it can't be used in the same ways (and shouldn't). class在Haskell是不一样的一class在Java中,或者说,它更接近一个接口,但它不能在相同的方式使用(也不应该)。 Haskell doesn't actually have a concept of inheritance or classes in the OOP sense, as it's not an OOP language. Haskell实际上并没有OOP意义上的继承或类的概念,因为它不是OOP语言。

However, if you want to have Eq and Show instances automatically for a type, just add them to the deriving clause of the data type. 但是,如果要为类型自动拥有EqShow实例,只需将它们添加到数据类型的deriving子句中即可。

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

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