Module

Hylograph.Optics.Tree

Package
purescript-hylograph-optics
Repository
afcondon/purescript-hylograph-optics

Tree Optics

Lenses, traversals, and folds for rose trees. These optics work with the Cofree-based Tree from psd3-tree.

#_root Source

_root :: forall a. Lens' (Tree a) a

Focus on the root value of a tree.

view _root (mkTree 1 [mkTree 2 [], mkTree 3 []])
-- => 1

set _root 100 tree
-- Changes root to 100, children unchanged

#_children Source

_children :: forall a. Lens' (Tree a) (List (Tree a))

Focus on the children of a tree (as a List of Trees).

view _children tree
-- => List of child trees

over _children (filter hasValue) tree
-- Filter children by some predicate

#_forest Source

_forest :: forall a. Lens' (Tree a) (Forest a)

Alias for _children (Forest = List Tree)

#_leaves Source

_leaves :: forall a. Traversal' (Tree a) a

Traverse all leaf nodes (nodes with no children).

toListOf _leaves tree
-- => List of all leaf values

over _leaves (*2) tree
-- Double all leaf values

#_branches Source

_branches :: forall a. Traversal' (Tree a) a

Traverse all branch nodes (nodes with children).

toListOf _branches tree
-- => List of all branch values

#_atDepth Source

_atDepth :: forall a. Int -> Traversal' (Tree a) a

Traverse all nodes at a specific depth. Depth 0 is the root, depth 1 is immediate children, etc.

toListOf (_atDepth 2) tree
-- => List of all grandchild values

#_allNodes Source

_allNodes :: forall a. Traversal' (Tree a) (Tree a)

Traverse ALL nodes in the tree (pre-order). Note: This traverses subtrees, not just values.

toListOf _allNodes tree
-- => Every subtree in the tree

#_childAt Source

_childAt :: forall a. Int -> Lens' (Tree a) (Maybe (Tree a))

Focus on a specific child by index. Returns Nothing if index out of bounds.

preview (_childAt 0) tree
-- => Maybe the first child

#nodeAtPath Source

nodeAtPath :: forall a. List Int -> Tree a -> Maybe (Tree a)

Get the node at a path if it exists. This is a simple accessor, not an optic.

nodeAtPath [0, 1, 2] tree
-- => Maybe the node at that path

#_matching Source

_matching :: forall a. (a -> Boolean) -> Traversal' (Tree a) a

Traverse nodes matching a predicate on their value.

toListOf (_matching (> 5)) tree
-- => All node values greater than 5

over (_matching isEven) (*2) tree
-- Double all even values