我有两种类型,Tree 和 BinTree。我实现比较的方式是这样的:
instance (Eq a) => Ord (Tree a) where
t <= u = traces t `subseteq` traces u
instance (Eq a) => Eq (Tree a) where
t == u = traces t `subseteq` traces u && traces u `subseteq` traces t
instance (Eq a) => Ord (BinTree a) where
t <= u = traces t `subseteq` traces u
instance (Eq a) => Eq (BinTree a) where
t == u = traces t `subseteq` traces u && traces u `subseteq` traces t
正如你所看到的,我的跟踪函数很乐意在 Tree 和 BinTree 上操作,因此我应该有一种方法可以做到: myBinTree < myTree
因此将 BinTree 与树进行比较
由于 BinTree 是 Tree 的子集,因此如何实现这一点以便可以比较 BinTree 和 Tree。
最佳答案
不会以这样的方式成为 Eq
的实例或Ord
类。这些类具有签名:
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
等等...
您可以编写自己的 (==)
函数,但是该函数会变得不明确,因此您始终需要指定哪个 (==)
> 您实际上正在说话的运算符(operator)。
您的评论“haskell 如何将 float 与整数进行比较?”的答案是它不会。如果你写:
> (1 :: Int) == (1.0 :: Float)
<interactive>:56:16:
Couldn't match expected type `Int' with actual type `Float'
In the second argument of `(==)', namely `(1.0 :: Float)'
In the expression: (1 :: Int) == (1.0 :: Float)
In an equation for `it': it = (1 :: Int) == (1.0 :: Float)
你看,无法进行比较。您可以通过转换来做到这一点:
> fromIntegral (1 :: Int) == (1.0 :: Float)
True
其中 fromIntegral
是将 Int
转换为(在本例中)Float
的函数。您可以通过实现 bin2tree
函数来执行相同的操作。
您当然可以定义自己的类似类:
class Similar a b where
(=~) :: a -> b -> Bool
(/=~) :: a -> b -> Bool
(/=~) x y = not $ x =~ y
(并在文件中添加 {-# LANGUAGE MultiParamTypeClasses #-}
作为修饰符)。
然后例如:
instance (Similar a b) => Similar [a] [b] where
(=~) [] [] = True
(=~) _ [] = False
(=~) [] _ = True
(=~) (x:xs) (y:ys) = (x =~ y) && (xs =~ ys)
但问题是您必须自己重新定义很多方法(使用 Eq
,如 nub
),以便它们与您的 一起使用类似的
类。
关于haskell - 比较 2 个相似类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28522038/