我需要在两个 Htree 之间进行比较,为此我实现了自己的比较函数,它与 sortBy 一起使用,但是我想实现 Eq 和 Ord 类的派生实例,但是覆盖所有可能组合所需的案例数量使得它不切实际的。
data Htree a b = Leaf a b
| Branch a (Htree a b) (Htree a b)
deriving (Show)
instance (Eq a) => Eq (Htree a b) where
(Leaf weight1 _ ) == (Leaf weight2 _) = weight1 == weight2
(Branch weight1 _ _) == (Leaf weight2 _) = weight1 == weight2
(Leaf weight1 _ ) == (Branch weight2 _ _) = weight1 == weight2
(Branch weight1 _ _) == (Branch weight2 _ _) = weight1 == weight2
如您所见,我只想比较 Htree 的单个部分,这将是实际代码中的 Integer,我需要为其编写四个案例。有没有办法概括这一点,所以我可以在一个案例中编写它?如果我比较两个 Htree,比较它们的整数部分?
我目前用来比较两个 htree 的是:
comparison :: Htree Integer (Maybe Char) -> Htree Integer (Maybe Char) ->
Ordering
comparison w1 w2 = if(getWeight(w1) > getWeight(w2)) then GT
else if(getWeight(w1) < getWeight(w2)) then LT
else EQ
其中 getWeight 定义为:
getWeight :: Htree Integer (Maybe Char) -> Integer
getWeight(Leaf weight _) = weight
getWeight(Branch weight _ _) = weight