for_tree

Macro for_tree 

Source
macro_rules! for_tree {
    ($var:ident in $init:expr; $cond:expr; $branch:expr => $body:block) => { ... };
    ($var:ident in $init:expr; $cond:expr; $branch:expr; $body:block) => { ... };
    ($var:ident = $init:expr; $cond:expr; $branch:expr => $body:block) => { ... };
    ($var:ident = $init:expr; $cond:expr; $branch:expr; $body:block) => { ... };
}
Expand description

A macro for traversing tree-like structures or generating tree-like data.

§Syntax

// This is just syntax illustration, not meant to be compiled
for_tree!(var in initial; condition; branches => {
    // body
    // You can use special control flow:
    // - break_tree!(); - exits the entire traversal
    // - prune!(); - skips traversing children of the current node
});

§Examples

Traverse a binary tree:

use arboriter::{for_tree, prune, break_tree, BinaryNode};

// Create a simple binary tree for demonstration
let root = BinaryNode::with_children(
    10,
    Some(Box::new(BinaryNode::new(5))),
    Some(Box::new(BinaryNode::new(15)))
);

for_tree!(node in &root; |_| true; |node| {
    // Explicitly declare the type of branches
    let mut branches: Vec<&BinaryNode<i32>> = Vec::new();
    if let Some(left) = &node.left {
        branches.push(left.as_ref());
    }
    if let Some(right) = &node.right {
        branches.push(right.as_ref());
    }
    branches
} => {
    println!("Node value: {}", node.value);

    if node.value == 10 {
        break_tree!(); // Exit the traversal
    }

    if node.value < 0 {
        prune!(); // Don't traverse children of negative nodes
    }
});

Generate strings of “a”, “b”, and “c” with length <= 8:

use arboriter::{for_tree, prune};

for_tree!(s in String::new(); |s| s.len() <= 8; |s| {
    // Create branches with explicit type
    let mut branches: Vec<String> = Vec::new();
    branches.push(format!("{}a", s));
    branches.push(format!("{}b", s));
    branches.push(format!("{}c", s));
    branches
} => {
    println!("{}", s);

    if s.len() == 8 {
        prune!(); // Don't generate longer strings
    }
});