【发布时间】:2013-08-10 03:11:30
【问题描述】:
作为学习haskell的一部分,我决定编写一个二叉树。
据我了解,如果我对大量插入和删除进行排序,即使结果树相对较小,当我最终开始评估时,我也很容易达到堆栈溢出。
这是我的问题:
我可以通过对我的函数引入一些严格性来避免这种情况吗? (带有 seq / deepseq 的东西?)。
在哪些情况下我希望将插入/删除保持在当前状态?
如果您觉得我的代码设计不当或不正确,请随时更正或改进。
相关代码:
import Data.List
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Eq)
leaf x = Branch x Empty Empty
-- insert ------------------------------------
treeInsert :: (Eq a, Ord a) => Tree a -> a -> Tree a
treeInsert Empty x = leaf x
treeInsert (Branch y l r) x | x<y = Branch y (treeInsert l x) r
| x>y = Branch y l (treeInsert r x)
| otherwise = Branch x l r --edit
-- delete ------------------------------------
treeDelete :: (Eq a, Ord a) => Tree a -> a -> Tree a
treeDelete Empty _ = Empty
treeDelete (Branch y l r ) x | y<x = Branch y l (treeDelete r x)
| y>x = Branch y (treeDelete l x) r
| y==x = del' $ Branch y l r
where
-- if this Branch is a leaf dispose of it.
-- if branch has only one child return the child (skip over).
-- otherwise, replace this branch with its successor (the leftmost child of the right tree)
-- successor will be extracted from its original location.
del' ( Branch y Empty Empty ) = Empty
del' ( Branch y Empty r ) = r
del' ( Branch y l Empty ) = l
del' ( Branch y l r ) = Branch ySucc l rWithout_ySucc
where
( rWithout_ySucc, ySucc ) = leftmost r
where
leftmost ( Branch y Empty Empty ) = ( Empty, y )
leftmost ( Branch y Empty r ) = ( r, y )
leftmost ( Branch y l r ) = ( Branch y ll r, z ) where ( ll, z ) = leftmost l
【问题讨论】:
-
我不认为
treeInsert符合您的预期。 -
@augustss 请详细说明
-
插入的东西已经存在时怎么办?
-
替换它,它是一棵没有重复的树。
-
它在我看来就像扔掉了左右分支。
标签: haskell optimization lazy-evaluation strict