鑑於從TypeClassopedia以下數據類型:代數數據類型和平等
data Cons a = Cons a (Cons a) | Empty deriving (Show, Eq)
我實現了其罪惡的函子實現:
instance Functor Cons where
fmap _ Empty = Empty
fmap f (Cons x xs) = Cons (f x) (Cons (f x) (fmap f xs))
於是,我試圖寫一個函數(快速檢查財產)需要Cons a
並返回一個Bool
:
prop_id_functor_law :: Cons a -> Bool
prop_id_functor_law x = fmap id x == id x
不過,我得到一個編譯時錯誤:
Prelude> :l EvilFunctor
[1 of 1] Compiling EvilFunctor (EvilFunctor.hs, interpreted)
EvilFunctor.hs:18:23:
No instance for (Eq a) arising from a use of `=='
Possible fix:
add (Eq a) to the context of
the type signature for prop_id :: Cons a -> Bool
In the expression: fmap id x == id x
In an equation for `prop_id': prop_id x = fmap id x == id x
Failed, modules loaded: none.
我粗略的直覺是,這個編譯時錯誤是有道理的。兩個a
怎麼可以比較除非他們實現了Eq
類型?
然而,當我定義data Cons a
時,deriving ... Eq
甚至可以做什麼?