哈斯克爾替代類和虛函數可以說我有以下ADT,警衛
data Properties a = Property String a
deriving (Show,Eq)
我已經做了以下情況吧,
instance Functor Properties where
fmap f (Property name prop) = Property name (f prop)
--
instance Applicative (Properties) where
pure a = Property "" a
(Property _ f) <*> p = fmap f p
instance Monad (Properties) where
return a = Property "" a
(Property name prop) >>= f = (f prop)
到目前爲止好。讓我們看看我們可以迄今爲止做,
pColors = Property "Color" ["Blue", "Red", "White"]
pNationality = Property "Nationality" ["Italian", "Norwegian", "Spanish"]
answers = do
color <- fmap permutations pColors
nation <- fmap permutations pNationality
return $ zip color nation
給人,
*Main> answers
Property "" [(["Blue","Red","White"],["Italian","Norwegian","Spanish"]),(["Red","Blue","White"],["Norwegian","Italian","Spanish"]),(["White","Red","Blue"],["Spanish","Norwegian","Italian"]),(["Red","White","Blue"],["Norwegian","Spanish","Italian"]),(["White","Blue","Red"],["Spanish","Italian","Norwegian"]),(["Blue","White","Red"],["Italian","Spanish","Norwegian"])]
所以fmap
和預期的單子綁定都在工作。現在我想使用alternative
中的guard
函數。基本上我想根據一些謂詞修剪pColors
和pNationality
。所以我嘗試定義,
instance Alternative (Properties) where
empty = Property "" []
但是,這給了我一個錯誤,我認爲(請糾正我,如果我錯了),這是因爲Haskell是解釋[]
從a
不同。但我認爲a
可能是任何東西,而[]
是其中之一,所以問題是什麼?
如果您使用'{ - #LANGUAGE GeneralizedNewtypeDivingiving# - }' – 4castle
您可以執行'newtype屬性a =屬性(String,a)派生(Show,Eq,Functor,Applicative,Monad)'上面的ADT?如果我編寫'newtype Property a = String a derivation(Show,Eq,Functor,Applicative,Monad)',它自己假設(避免多個'Property'的聲明)'給出一個錯誤,Functor不能派生出來並且不得不使用'DerivedFunctor'。 – ITA
並加入'DerivedFunctor'則誤差變, '不能讓「應用型住宅」 (甚至狡猾GeneralizedNewtypeDeriving)的衍生實例: 不能ETA-減少表示類型enough' – ITA