簡體   English   中英

使用類型類Ord的方法的無限循環

[英]Infinite loop with method of the typeclass Ord

我定義了一種數據類型:

Data Card = Card Int deriving (Show, Eq)

(我也定義了一個類型同義詞:

Type Cards = [Card]

然后使它成為:

 instance Ord Card where
    x > y   |ix == iy   = False
            |ix == 0    = True
            |iy == 0    = False
            |otherwise  = (ix > iy)
        where 
            ix = label x
            iy = label y

然后當我輸入:

 (Card x) > (Card y) :: x,y are Int 

它工作,但當我輸入:

 [(Card x)] > [(Card y)] :: x,y are Int 

它進入循環。

為什么會這樣? 我如何解決它?

Card Ord實例僅定義> ,但您需要定義<=compare

最小完整定義: compare<=

Ord的名單實例定義compare底層數據方面類型的compare 默認情況下, compare<=是相互定義的,因此如果您沒有定義其中任何一個,它們在調用時不會終止。 列表的其他Ord操作(包括> )是根據compare來定義的,因此當您在[Card]上調用它時,為什么>不會終止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM