简体   繁体   中英

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

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:

 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

Tamas

You have to provide your own elem . What is elem 's type?

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

However, your traffic light doesn't have an Eq instance. It has a Eq1 instance.

You have to write your own elem1 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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