【发布时间】:2019-04-08 07:20:08
【问题描述】:
我正在尝试创建一个名为“insertm”的函数,该函数应该将键和值插入二叉树。如果键已经存在,它应该返回“无”。如果不是,它应该根据它的值将键和值插入到树中。我能够完成大部分工作,但是我遇到了一个错误,我不确定如何修复。
这是一个例子:
TestQ4> insertm 25 "vw" t5
Just (10:"ghi")<$,(30:"def")<(20:"abc")<$,(25:"vw")>,$>>
TestQ4> insertm 20 "vw" t5
Nothing
这是我的代码:
data BinaryTree a b = Leaf | Node a b (BinaryTree a b) (BinaryTree a b)
insertm :: (Ord a, Show a, Show b) =>
a -> b -> BinaryTree a b -> Maybe (BinaryTree a b)
insertm val key Leaf = Just (Node val key Leaf Leaf)
insertm x y (Node val key left right)
| x == val = Nothing
| x < val = Just (Node val key (insertm x y left) right)
| otherwise = Just (Node val key left (insertm x y right))
这是我得到的错误:
* Couldn't match expected type `BinaryTree a b'
with actual type `Maybe (BinaryTree a b)'
* In the fourth argument of `Node', namely `(insertm x y right)'
In the first argument of `Just', namely
`(Node val key left (insertm x y right))'
In the expression: Just (Node val key left (insertm x y right))
* Relevant bindings include
right :: BinaryTree a b (bound at TestQ4.hs:101:32)
left :: BinaryTree a b (bound at TestQ4.hs:101:27)
key :: b (bound at TestQ4.hs:101:23)
val :: a (bound at TestQ4.hs:101:19)
y :: b (bound at TestQ4.hs:101:11)
x :: a (bound at TestQ4.hs:101:9)
(Some bindings suppressed; use -fmax-relevant-binds=N or -fno-max-
relevant-binds)
| x < val = Just (Node val key (insertm x y left) right)
^^^^^^^^^^^^^^^^
我也收到了我的其他情况的错误。所以我有点卡住任何帮助将不胜感激。
【问题讨论】:
标签: haskell recursion binary-tree