Skip to main content

simple/
simple.rs

1//! Minimal example showing the new observer-based API
2//!
3//! This demonstrates:
4//! - Creating graphs with observers
5//! - Dynamic node creation
6//! - Automatic change notifications
7
8use neal::{DerivedNode, Graph, GraphError, InputNode, Operation};
9use std::hash::Hash;
10
11#[derive(Clone, PartialEq, Hash)]
12struct Number(i32);
13
14// Operations for our Number type
15struct Add;
16impl Operation<(Number, Number), Number> for Add {
17    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Number, GraphError> {
18        let a = inputs[0]
19            .as_any()
20            .downcast_ref::<Number>()
21            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
22        let b = inputs[1]
23            .as_any()
24            .downcast_ref::<Number>()
25            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
26        Ok(Number(a.0 + b.0))
27    }
28
29    fn input_count(&self) -> Option<usize> {
30        Some(2)
31    }
32}
33
34struct Multiply;
35impl Operation<(Number, Number), Number> for Multiply {
36    fn execute(&self, inputs: &[&dyn neal::Value]) -> Result<Number, GraphError> {
37        let a = inputs[0]
38            .as_any()
39            .downcast_ref::<Number>()
40            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
41        let b = inputs[1]
42            .as_any()
43            .downcast_ref::<Number>()
44            .ok_or_else(|| GraphError::InvalidOperation("Expected Number".into()))?;
45        Ok(Number(a.0 * b.0))
46    }
47
48    fn input_count(&self) -> Option<usize> {
49        Some(2)
50    }
51}
52
53fn main() -> Result<(), GraphError> {
54    let mut graph = Graph::new();
55
56    // Build a simple computation: (5 + 3) * 2 using new API
57    let a = graph.add_node(InputNode::new(Number(5)));
58    let b = graph.add_node(InputNode::new(Number(3)));
59    let c = graph.add_node(InputNode::new(Number(2)));
60
61    let sum = graph.add_node(DerivedNode::new(vec![a.id(), b.id()], Add));
62
63    let result = graph.add_node(DerivedNode::new(vec![sum.id(), c.id()], Multiply));
64
65    // Compute
66    graph.compute()?;
67
68    if let Some(value) = result.get_value(&graph) {
69        println!("(5 + 3) * 2 = {}", value.0);
70    }
71
72    // Update and recompute
73    a.set_value(&mut graph, Number(10))?;
74    graph.compute()?;
75
76    if let Some(value) = result.get_value(&graph) {
77        println!("(10 + 3) * 2 = {}", value.0);
78    }
79
80    Ok(())
81}