jxxcarlson/tree-extra/1.0.1

Tree.Extra

Manipulate Trees

attachSubtree : a -> Tree a -> Tree a -> Maybe (Tree a)
> a = t 1 [ t 2 [ s 3, t 4 [s 5, s 6]]]
> x = t 2 [ s 3, s 4]


> attachSubtree 1 x a
Just (Tree 1 [Tree 2 [Tree 3 [],Tree 4 [Tree 5 [],Tree 6 []]],Tree 2 [Tree 3 [],Tree 4 []]])
removeSubtree : a -> Tree a -> Maybe (Tree a)
> a = t 1 [ t 2 [ s 3, t 4 [s 5, s 6]]]
Tree 1 [Tree 2 [Tree 3 [],Tree 4 [Tree 5 [],Tree 6 []]]]


> removeSubtree 3 a |> Maybe.andThen (removeSubtree 5)
Just (Tree 1 [Tree 2 [Tree 4 [Tree 6 []]]])
moveSubtree : a -> a -> Tree a -> Maybe (Tree a)
> a = t 1 [ t 2 [ s 3, t 4 [s 5, s 6]]]
Tree 1 [Tree 2 [Tree 3 [],Tree 4 [Tree 5 [],Tree 6 []]]]


> moveSubtree 4 1 a
Just (Tree 1 [Tree 2 [Tree 3 []],Tree 4 [Tree 5 [],Tree 6 []]])
spanningTree : List a -> Tree a -> Maybe (Tree a)

Compute the smallest subtree of the given tree which contains all the nodes of the nodeList.

> a = t 1 [ t 2 [ s 3, t 4 [s 5, s 6]]]
Tree 1 [Tree 2 [Tree 3 [],Tree 4 [Tree 5 [],Tree 6 []]]]


> spanningTree [3, 5] a
Just (Tree 2 [Tree 3 [],Tree 4 [Tree 5 [],Tree 6 []]])

Manipulate using a partial order on nodes

attachSubtreeInOrder : (a -> a -> Bool) -> a -> Tree a -> Tree a -> Maybe (Tree a)

The function

attachSubtreeInOrder bigger targetNode subTree tree

seeks to attach a subtree to a given tree is such a way that the parent of the subtree has the proper order with respect to the function

bigger : a -> a -> Bool

namely,

  • it is greater than the root of the subtree

  • it is greater than or equal to targetNode

  • it is the least such node

Here is an example:

> a = t 1 [ t 2 [ s 3, t 4 [s 5, s 6]]]
> Tree 1 [Tree 2 [Tree 3 [],Tree 4 [Tree 5 [],Tree 6 []]]]


> x = t 3 [ s 4, s 5]
> Tree 3 [Tree 4 [],Tree 5 []]


> attachSubtreeInOrder (<) 6 x a
> Just (Tree 1 [Tree 2 [Tree 3 [],Tree 4 [Tree 5 [],Tree 6 []],Tree 3 [Tree 4 [],Tree 5 []]]])

Info on Trees

depth : Tree a -> Int
> a = t 1 [ t 2 [ s 3, t 4 [s 5, s 6]]]


> depth a
3
nodeCount : Tree a -> Int

Number of notes in a tree

    > a = t 1 [ t 2 [ s 3, t 4 [s 5, s 6]]]


    > nodeCount a
    6
tagWithDepth : Tree a -> Tree ( a, Int )

Transforms a tree of items into a tree of tuples of the form (a, k), where k is the depth of a in the tree.

> a = t 1 [ t 2 [ s 3, t 4 [s 5, s 6]]]


> tagWithDepth a
> Tree (1,0) [Tree (2,1) [Tree (3,2) [],Tree (4,2) [Tree (5,3) [],Tree (6,3) []]]]