简体   繁体   中英

Get the parent of a node in Data.Tree (haskell)

I need a tree implementation where I can access the parent node of any node in the tree. Looking at Data.Tree I see the tree definition:

data Tree a = Node {
    rootLabel :: a,         -- ^ label value
    subForest :: Forest a   -- ^ zero or more child trees
}

So if I have a tree node Tree a I can access its label and its children. But it is also possible to access its parent node? Do have to choose a different implementation for my needs? Which package would you recommend?

If I'm not mistaken, what you're asking for is basically what gets implemented in LYAH's section on Zippers .

I won't attempt to explain it better than Miran did, but the basic idea is to keep track of which tree you're coming from, as well as which branch you're moving down, while you traverse the tree. You're not keeping track of the node's parent directly in the data structure, but all of the information will be available when you traverse the tree.

Data.Tree deliberately does not have nodes reference their own parents. This way, changes to parent nodes (or nodes in other branches) do not need to re-create the entire tree, and nodes in memory may be shared with multiple trees. The term for structures like this is "persistent".

You may implement a node which knows its own parent; the resulting structure will not be persistent. The clear alternative is to always know where the root node of your tree is; that's good practice in any language.

One library that does allow Data.Tree to know its parents is rosezipper, documentation can be found here .

Try this:

 data Tree a = Leaf | Node a (Tree a) (Tree a) (Tree a) deriving (Eq, Show)

You can save the parent tree into the third(or any other) tree. Example:

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 t@(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 t@(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* in this row you can save the whole parent:

 where insertIt x Leaf parent = Node x Leaf Leaf parent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM