![](/img/trans.png)
[英]Is the infinite list capacity built into the `Ord` typeclass, or a product of haskell's definition of a number?
[英]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.