作为学习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