Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 比较两种相似的类型?_Haskell - Fatal编程技术网

Haskell 比较两种相似的类型?

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

我有两种类型,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
实例(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)