haskell - 比较 2 个相似类型?

标签 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 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/

相关文章:

c - 为什么 Haskell 在执行类似 C 的代码时表现如此糟糕? (至少在这种情况下)

haskell - 如何在 Haskell 中派生多个 Functor 实例?

haskell - 修改成员变量的惯用方法

function - 在 haskell 中优雅地定义许多函数值

haskell - 函数在类型级别上的模式匹配是可能的,但在值级别上则不行,为什么会出现这种差异?

haskell - 如何让 Haskell 的 TChan 像 Erlang 的消息队列一样延迟消息?

haskell - 'State' 的数据构造函数在哪里?

haskell - 是否可以并行运行多个提示实例?

haskell - Haskell 中是否有定点运算符?

haskell - 如何向秒差距中的给定位置发出失败消息