Haskell 比较两种相似的类型?
我有两种类型,Tree和BinTree。我实现比较的方式如下:Haskell 比较两种相似的类型?,haskell,Haskell,我有两种类型,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
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
实例(Eq a)=>Ord(树a),其中
t Eq(树a)在哪里
t==u=tracest`subsetq`traces u&&traces u`subsetq`tracest
实例(等式a)=>Ord(二叉树a),其中
t等式(二叉树a)其中
t==u=tracest`subsetq`traces u&&traces u`subsetq`tracest
正如您所看到的,我的traces函数很乐意在Tree和BinTree上运行,因此我应该有一种方法可以做到:
myBinTree由于二叉树是树的一个子集,如何实现这一点,以便能够比较二叉树和树。不是以这样的方式,它会成为或类的实例。这些类具有以下特征:
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
等等
您可以编写自己的(==)
函数,但该函数会变得模棱两可,因此您始终需要指定您实际使用的(==)
运算符
对于您的评论“haskell如何将浮点与整数进行比较?”的答案是它没有。如果你写:
> (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)
其中,from integral
是一个函数,它将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
),这样它们才能与你的类似的类一起工作。你可以比较树
s.@Cirdec是的,但是有没有一种方法可以做到这一点,我可以使用“否”。这两个参数必须是相同的类型。haskell如何将浮点与整数进行比较?haskell不会将浮点与整数进行比较。当你写1.7<3
时,真正的类型是1.7::分数a=>a
和3::Num a=>a
。Haskell已经并将决定a
是Double
(默认情况下,它尝试Integer
,然后Double
,然后放弃)。如果我们显式地写1.7<(3::Integer)
我们会得到一个类型错误;Haskell无法将双精度
1.7
与整数
进行比较。
instance (Similar a b) => Similar [a] [b] where
(=~) [] [] = True
(=~) _ [] = False
(=~) [] _ = True
(=~) (x:xs) (y:ys) = (x =~ y) && (xs =~ ys)