0

我对 Haskell 中的 BST 有疑问。我想我在将 Node(Uzel) 中的“关键”变量定义为 Ord 时遇到了问题。但我绝对没有更多的想法。

不过,如果我曾经将 Tree 类型的“key”参数定义为 Ord,那么它是有效的,并且代码中的每次使用也会获得此信息。

以下代码不完整,但我正在谈论的事情是:

data (Ord key) => Tree key value = List key value |Uzel (Tree key value) key value (Tree key value) | Null deriving (Show)

prazdny :: Ord key => Tree key value
prazdny = Null

najdi :: (Ord key,Ord k) => k -> Tree key value -> Maybe a
najdi k Null = Nothing
najdi k (Uzel levy klic hodnota pravy) = if k < klic
                then najdi k levy
                else najdi k pravy

当试图编译我得到这个:

bvs.hs:9:49:
Could not deduce (key ~ k)
from the context (Ord key, Ord k)
  bound by the type signature for
             najdi :: (Ord key, Ord k) => k -> Tree key value -> Maybe a
  at bvs.hs:(8,1)-(11,58)
  `key' is a rigid type variable bound by
        the type signature for
          najdi :: (Ord key, Ord k) => k -> Tree key value -> Maybe a
        at bvs.hs:8:1
  `k' is a rigid type variable bound by
      the type signature for
        najdi :: (Ord key, Ord k) => k -> Tree key value -> Maybe a
      at bvs.hs:8:1
In the second argument of `(<)', namely `klic'
In the expression: k < klic
In the expression: if k < klic then najdi k levy else najdi k pravy

非常感谢您的任何想法!

4

2 回答 2

2

问题是 k 和 key 必须是相同类型才能比较它们,但是您声明它们可能不同,因此编译器会抱怨。如果您使它们具有相同的类型,它将进行类型检查。

于 2012-05-19T02:01:46.777 回答
0

注释掉这一行,它会编译:

--najdi :: (Ord key,Ord k) => k -> Tree key value -> Maybe a
于 2012-05-17T23:48:53.053 回答