简体   繁体   English

没有因使用'elem'而引起的(Eq TrafficLight)实例可能的解决方法:为(Eq TrafficLight)添加实例声明

[英]No instance for (Eq TrafficLight) arising from a use of `elem' Possible fix: add an instance declaration for (Eq TrafficLight)

I have an example from Learn You a Haskell for Great Good named 我有一个名为“为善良而学的Haskell”的示例,名为

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]

and the first three rows are work, but the last line contains elem doesn't, got an error: 并且前三行有效,但最后一行包含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]'

I look for the solution how can I add an instance for the marked part, but didn't find hints about the topic, I am new in Haskell so thanks in advance 我正在寻找解决方案,如何为标记的零件添加实例,但是没有找到有关该主题的提示,我是Haskell的新手,所以在此先感谢

Tamas 塔马斯

You have to provide your own elem . 您必须提供自己的elem What is elem 's type? elem的类型是什么?

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

However, your traffic light doesn't have an Eq instance. 但是,您的交通信号灯没有Eq实例。 It has a Eq1 instance. 它具有一个Eq1实例。

You have to write your own elem1 : 您必须编写自己的elem1

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM