0

我需要在两个 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
4

1 回答 1

7

做你想做的,首先写一个更通用的版本(即多态版本)getWeight,只需要重写类型签名:

getWeight :: Htree a b -> a
getWeight(Leaf weight _) = weight
getWeight(Branch weight _ _) = weight

然后您可以执行以下操作(在使用函数之后import-onData.Function还按照@FyodorSolkin 的建议重写了它们以使它们变得自由)

instance (Eq a) => Eq (Htree a b) where
    (==) = (==) `on` getWeight

instance (Ord a) => Ord (Htree a b) where
    compare = compare `on` getWeight
于 2019-02-12T15:22:16.187 回答