試試這個:
data Tree a = Leaf | Node a (Tree a) (Tree a) (Tree a) deriving (Eq, Show)
您可以將父樹保存到第三(或任何其他)樹。 例子:
singleton::(Ord a)=>a->Tree a
singleton x = Node x Leaf Leaf Leaf
insert::(Ord a)=>a->Tree a->Tree a
insert x Leaf = singleton x
insert x [email protected](Node a l r p) = insertIt x t p
where insertIt x Leaf (Node a l r p) = Node x Leaf Leaf (Node a Leaf Leaf Leaf)--1*
insertIt x [email protected](Node a l r p) parent
| x == a = t
| x < a = Node a (insertIt x l t) r p
| x > a = Node a l (insertIt x l t) p
1此行*您可以保存整個父:
where insertIt x Leaf parent = Node x Leaf Leaf parent
_你爲什麼要去?如果你想修改一些'''',看看[拉鍊](http://www.haskell.org/haskellwiki/Zipper)。這是一個深深的兔子洞,像「Comonad」這樣可怕的詞。 (這比Monads恕我直言。)更容易 – Franky
你應該寫一個函數來交付你的父母。例如:'findPath :: Eq a => a - > Tree a - > [Tree a]'。如果你想改變完整樹的部分,寫一個類似於'updateNode :: Eq a => a - >([Tree a] - > Tree a) - > Tree a - > Tree a'的函數。這真的取決於你想做什麼。 – Vektorweg