使用“elem”时没有(Eq TrafficLight)的实例可能的修复:为(Eq TrafficLight)添加实例声明

时间:2017-02-18 12:23:17

标签: haskell

我有一个例子来自于了解你是一个名为

的Haskell for Great Good
class 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

1 个答案:

答案 0 :(得分:5)

您必须提供自己的elem。什么是elem的类型?

elem :: Eq a => a -> [a] -> Bool

但是,您的红绿灯没有Eq个实例。它有一个Eq1实例。

您必须自己编写elem1

elem1 :: Eq1 a => a -> [a] -> Bool
elem1 y xs = -- exercise