在haskell的二进制搜索树,比较

时间:2012-05-17 22:00:29

标签: haskell binary-search-tree

我在Haskell中遇到BST问题。 我想我将Node(Uzel)中的“key”变量定义为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

非常感谢任何想法!!

2 个答案:

答案 0 :(得分:2)

问题是k和key必须是相同的类型才能比较它们,但是你声明它们可能是不同的,所以编译器会抱怨。如果你将它们设为相同的类型,它将键入check。

答案 1 :(得分:0)

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

--najdi :: (Ord key,Ord k) => k -> Tree key value -> Maybe a