0
我是否正確地說下面是一個使用數據類型實例的例子(一個單調乏味的例子)?即允許您爲不同的數據定義不同的行爲。數據類型實例?
如果不是,它們還能如何使用?
代碼:
data HealthIndicators = Weight | Age | BloodPressure deriving (Show)
data IrrelevantIndicators = Starsign | BirthMonth | IQ deriving (Show)
class IndicatorTest a where
indicatortest :: a -> Bool
instance IndicatorTest HealthIndicators where
indicatortest Weight = True
indicatortest Age = True
indicatortest BloodPressure = True
instance IndicatorTest IrrelevantIndicators where
indicatortest Starsign = False
indicatortest BirthMonth = False
indicatortest IQ = False
它可以很容易地定義類型安全[平等](https://hackage.haskell.org/package/base-4.9.0.0/docs/Prelude.html#t:Eq),排序等,和甚至沒有考慮到類型類可以超越更高級的類型(比如[monads])(https://hackage.haskell.org/package/base-4.9.0.0/docs/Prelude.html#t :Monad)或箭頭) – Alec
嗯,這是真的,但通常會使用兩種不同的功能。或者在不同的模塊中定義兩個同名的函數。在絕大多數情況下,我們不需要像OOP那樣的動態分派。儘管如此,你的例子在技術上是正確的,但我發現例如「Ord,Eq,Show,Monoid ......」更加有趣和普遍。你可能想看看他們。 – chi
是的,一個可能的目標是找到不同數據類型的常見用途。這很可能是使用原始作者所說的數據類型甚至沒有想象的。話雖如此,我並不認爲這個例子構成了一個很好的數據模型。 – Ingo