是否可以为 haskell 中的数据类型编写通用派生实例?
Is it possible to write a generall derived instance for a data type in haskell?
我需要在两个 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,我需要为它写四个case。有没有一种方法可以概括这一点,以便我可以将其写在一个案例中?
如果我比较两个 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
为所欲为,先写一个getWeight
更通用的版本(即多态版本),只需要重写类型签名:
getWeight :: Htree a b -> a
getWeight(Leaf weight _) = weight
getWeight(Branch weight _ _) = weight
然后你可以执行以下操作(在 import
ing Data.Function
中的 on
函数之后 - 我还按照@FyodorSolkin 的建议重写了它们的点)
instance (Eq a) => Eq (Htree a b) where
(==) = (==) `on` getWeight
instance (Ord a) => Ord (Htree a b) where
compare = compare `on` getWeight
我需要在两个 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,我需要为它写四个case。有没有一种方法可以概括这一点,以便我可以将其写在一个案例中? 如果我比较两个 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
为所欲为,先写一个getWeight
更通用的版本(即多态版本),只需要重写类型签名:
getWeight :: Htree a b -> a
getWeight(Leaf weight _) = weight
getWeight(Branch weight _ _) = weight
然后你可以执行以下操作(在 import
ing Data.Function
中的 on
函数之后 - 我还按照@FyodorSolkin 的建议重写了它们的点)
instance (Eq a) => Eq (Htree a b) where
(==) = (==) `on` getWeight
instance (Ord a) => Ord (Htree a b) where
compare = compare `on` getWeight