rlh*_*lhh 7 haskell types functional-programming
有人可以向我解释如何创建自定义数据类型?
**我不允许对Suit本身进行修改,例如.派生(Eq,Ord)
data Suit = Clubs | Diamonds | Hearts | Spades deriving (Eq)
Run Code Online (Sandbox Code Playgroud)
我的尝试:
instance Ord Suit where
compare suit1 suit2 = compare suit1 suit2
Run Code Online (Sandbox Code Playgroud)
但这似乎是一个连续的循环,并没有停止.
Ord的定义看起来像(但不完全)
class Ord a where
compare :: a -> a -> Ordering
Run Code Online (Sandbox Code Playgroud)
并Ordering
有三个可能的值:LT, EQ, GT
.
因此,您需要定义每个比较的结果.就像是:
instance Ord Suit where
compare Clubs Diamonds = LT
compare Diamonds Clubs = GT
compare Diamonds Diamonds = EQ
compare Diamonds _ = LT -- Diamonds are lower than everything besides Clubs and Diamonds
Run Code Online (Sandbox Code Playgroud)
您的实际订购可能会有所不同,但这应该为您提供基本的想法.
一种编写自定义Ord
实例的方法,您不必拼写每个比较的结果是:
instance Ord Suit where
compare a b = compare (relativeRank a) (relativeRank b) where
relativeRank Diamonds = 1
relativeRank Clubs = 2
relativeRank Hearts = 3
relativeRank Spades = 4
Run Code Online (Sandbox Code Playgroud)
在这里,您只需要提及每个构造函数一次,就可以轻松决定不同的顺序。
您也可以使用compare Data.Function.on relativeRank
,但这可能更容易理解。