Skip to main content

unfold

Function unfold 

Source
pub fn unfold<A, V>(expand: impl Fn(A) -> (V, Vec<A>), seed: A) -> Pattern<V>
Expand description

Anamorphism: expand a seed into a Pattern<V> tree.

expand receives a seed and returns the value for the current node plus a list of child seeds. The tree is built iteratively (work stack) to avoid stack overflow for arbitrarily deep hierarchies.

ยงExamples

use pattern_core::unfold;

// Build a depth-3 binary tree from a depth seed
let tree = unfold(|depth: u32| {
    if depth == 0 {
        (depth, vec![])
    } else {
        (depth, vec![depth - 1, depth - 1])
    }
}, 2u32);

assert_eq!(tree.value, 2);
assert_eq!(tree.elements.len(), 2);
assert_eq!(tree.elements[0].value, 1);