【问题标题】:implementing binary search tree insertion in Haskell在 Haskell 中实现二叉搜索树插入
【发布时间】:2014-01-18 08:49:49
【问题描述】:

我正在实现一个 BST 的插入功能,下面是我的代码:

data Tree a = Empty | Branch a (Tree a) (Tree a) 
    deriving (Show, Eq)

tinsert             :: Tree a -> a -> Tree a 
tinsert Empty a         = Branch a Empty Empty
tinsert (Branch a left right) b
    | b == a = Branch a left right
    | b < a = Branch a (tinsert left b) right
    | b > a = Branch a left (tinsert right b)

当我在ghci中加载这个函数时,它给了我很多错误,这似乎与比较部分有关。我看不出有什么问题。我是Haskell的新手,有人可以帮忙吗?非常感谢。

【问题讨论】:

  • 请添加您收到的错误消息的详细信息以及您尝试解决的问题。
  • 由于您要比较树中的对象,它们必须是 Ord 类型类的成员。 &lt; 的类型是 Ord a =&gt; a -&gt; a -&gt; Bool。您的函数的正确类型是Ord a =&gt; Tree a -&gt; a -&gt; Tree a

标签: haskell insert binary-search-tree


【解决方案1】:

tinsert的类型改为

tinsert :: (Ord a) => Tree a -> a -> Tree a 

修复它。

这是必要的,因为函数 (&lt;)(&gt;) 来自 Ord 类型类,您需要在类型签名中拥有它。

你也使用==(==) :: Eq a =&gt; a -&gt; a -&gt; Bool,但是EqOrd的超类,所以编译器知道如果你有(&lt;)可用,你已经有==,所以你不需要也需要说Eq a

【讨论】:

  • 嗨,克里斯,非常感谢,但实际上是 tinsert :: (Ord a) =》 Tree a -> a -> Tree a。我修好了它。感谢您的信息。
猜你喜欢
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多