簡體   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)

我有一個名為“為善良而學的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]

並且前三行有效,但最后一行包含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的新手,所以在此先感謝

塔馬斯

您必須提供自己的elem elem的類型是什么?

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

但是,您的交通信號燈沒有Eq實例。 它具有一個Eq1實例。

您必須編寫自己的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