将清单插入Haskell中的二进制树
基本上,我试图将元素从列表中插入二进制树中,或者这是我认为在将列表插入到树时应该做的。
这是我的树插入:
data Tree = EmptyTree | Node Integer Tree Tree deriving (Show, Eq, Ord)
insertElement x EmptyTree = Node x EmptyTree EmptyTree
insertElement x (Node a left right) = if x == a
then (Node x left right)
else if x < a
then (Node a (insertElement x left) right)
else
Node a left (insertElement x right)
我认为我可以使用地图从列表中获取元素并将其插入列表中。
类似的东西:inserer x = map(insertelement x eytictree)
我可以使用插入者列表并将其插入列表中。
但是,我认为这个代码几乎是不正确的,我想知道我该怎么做?
Basically, I'm trying to insert elements from the list into the binary tree one by one, or that's what I thought it should be done when inserting list to the tree.
Here is my tree for inserting:
data Tree = EmptyTree | Node Integer Tree Tree deriving (Show, Eq, Ord)
insertElement x EmptyTree = Node x EmptyTree EmptyTree
insertElement x (Node a left right) = if x == a
then (Node x left right)
else if x < a
then (Node a (insertElement x left) right)
else
Node a left (insertElement x right)
and I thought I could use map to get elements from list and insert it into the list.
Something like this: inserter x = map (insertElement x EmptyTree)
where I get list with inserter and insert it into the list.
But, this code is pretty much incorrect I think, and I was wondering how can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将使用
inserer xs = map(`insertelement` ofterytree)
将创建一个树的列表,其中每个项目都会插入一次。您能做的就是使用 foldl ::折叠t =&gt; (b - &gt; a - &gt; b) - &gt; b - &gt; ta-&gt; b 或
foldr ::折叠t =&gt; (a - &gt; b - &gt; b) - &gt; b - &gt; ta-&gt; 每次通过累加器,到
目
b 树,因此使用
inserer
将项目的折叠
插入到tree> tree
可能已经包含项目的,例如:If you would use
inserter xs = map (`insertElement` EmptyTree)
you will create a list of trees where each item is inserted once.What you can do is use
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b
orfoldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
to each time pass the accumulator, the thus far build up list, and thus insert the next item, so:or:
It might however make more sense to allow to specify the base tree, and thus using
inserter
to insert aFoldable
of items to aTree
that might already contain items, for example: