我有一个例子来自于了解你是一个名为
的Haskell for Great Goodclass Eq1 a where
(===), (=/=) :: a -> a -> Bool
x === y = not $ x =/= y
x =/= y = not $ x === y
data TrafficLight = Red | Yellow | Green
instance Eq1 TrafficLight where
Red === Red = True
Green === Green = True
Yellow === Yellow = True
_ === _ = False
instance Show TrafficLight where
show Red = "Red light"
show Yellow = "Yellow light"
show Green = "Green light"
main = do
print $ Red === Red
print $ Red === Yellow
print $ [Red, Yellow, Green]
print $ Red `elem` [Red, Yellow, Green]
并且前三行有效,但最后一行包含elem
没有,出错:
No instance for (Eq TrafficLight) arising from a use of `elem'
Possible fix: add an instance declaration for (Eq TrafficLight)
In the second argument of `($)', namely
`Red `elem` [Red, Yellow, Green]'
我寻找解决方案如何为标记的部分添加实例,但没有找到关于该主题的提示,我是Haskell的新人,所以提前感谢
的Tamas
答案 0 :(得分:5)
您必须提供自己的elem
。什么是elem
的类型?
elem :: Eq a => a -> [a] -> Bool
但是,您的红绿灯没有Eq
个实例。它有一个Eq1
实例。
您必须自己编写elem1
:
elem1 :: Eq1 a => a -> [a] -> Bool
elem1 y xs = -- exercise