2016-09-22 45 views
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 
+0

它可以很容易地定義類型安全[平等](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

+0

嗯,這是真的,但通常會使用兩種不同的功能。或者在不同的模塊中定義兩個同名的函數。在絕大多數情況下,我們不需要像OOP那樣的動態分派。儘管如此,你的例子在技術上是正確的,但我發現例如「Ord,Eq,Show,Monoid ......」更加有趣和普遍。你可能想看看他們。 – chi

+0

是的,一個可能的目標是找到不同數據類型的常見用途。這很可能是使用原始作者所說的數據類型甚至沒有想象的。話雖如此,我並不認爲這個例子構成了一個很好的數據模型。 – Ingo

回答

0

首先,你的情況下,不需要列出所有的情況下,因爲它們沒有任何區別。你可以寫

instance IndicatorTest HealthIndicators where 
    indicatortest _ = True 

或者,如果你願意的話,第二行可以

indicatortest = const True 

如果你正在寫這樣的功能,這可能是有用的:

foo :: (IndicatorTest h) => h -> String 

,你需要結果取決於類型h是否是有用的指標而有所不同。但是在這種情況下,無論如何,你可能已經在「IndicatorTest」類中創造了「foo」功能。

如果不知道自己實際上想要達到什麼目標,有點難以進一步提供建議。