[英]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中的多重繼承,將會很有幫助。
話
class (Eq a, Show a) => C a where
並不意味着實現C
類型自動實現Eq
和Show
,這意味着他們必須首先實現Eq
和Show
才能實現C
一class
在Haskell是不一樣的一class
在Java中,或者說,它更接近一個接口,但它不能在相同的方式使用(也不應該)。 Haskell實際上並沒有OOP意義上的繼承或類的概念,因為它不是OOP語言。
但是,如果要為類型自動擁有Eq
和Show
實例,只需將它們添加到數據類型的deriving
子句中即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.