簡體   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