Display as text

This commit is contained in:
Rendo 2025-11-09 11:58:50 +05:00
commit 80c9d47399
3 changed files with 61 additions and 1 deletions

View file

@ -53,4 +53,7 @@ impl Formula {
self.display_recursion(indent_level + 1, next_nodes); self.display_recursion(indent_level + 1, next_nodes);
} }
} }
pub fn as_text(&self) -> String {
self.tree.as_text()
}
} }

View file

@ -78,6 +78,26 @@ impl Node {
pub fn modify_tree(&mut self) -> NodeModifier { pub fn modify_tree(&mut self) -> NodeModifier {
NodeModifier::from_node(self, None) NodeModifier::from_node(self, None)
} }
pub fn as_text(&self) -> String {
let mut children_text = "".to_string();
if self.children.len() > 0 {
for i in 0..self.children.len() {
children_text += (&self.children[i]).as_text().as_str();
if i < self.children.len() - 1 {
children_text += ",";
}
}
}
match &self.handler {
NodeHandler::Function {
name,
function,
max_args,
} => name.clone() + "(" + children_text.as_str() + ")",
NodeHandler::Empty => children_text,
_ => self.to_string(),
}
}
} }
impl fmt::Display for Node { impl fmt::Display for Node {
@ -93,7 +113,7 @@ impl fmt::Display for Node {
max_args, max_args,
} => name.clone(), } => name.clone(),
NodeHandler::Variable => "X".to_string(), NodeHandler::Variable => "X".to_string(),
NodeHandler::Empty => "Empty".to_string(), NodeHandler::Empty => "".to_string(),
} }
) )
} }

View file

@ -52,3 +52,40 @@ fn test_branch_sum() {
let results = formula.run(vec![0f64, 1f64, 2f64, 3f64, 4f64, 5f64]); let results = formula.run(vec![0f64, 1f64, 2f64, 3f64, 4f64, 5f64]);
assert_eq!(results, vec![1f64, 2f64, 3f64, 4f64, 5f64, 6f64]) assert_eq!(results, vec![1f64, 2f64, 3f64, 4f64, 5f64, 6f64])
} }
#[test]
fn test_display_as_text() {
let mut formula = Formula::new();
assert!(
formula
.modify_tree()
.insert_node(
Node::function("sum".to_string(), |inputs| inputs.iter().sum(), None),
None
)
.is_err()
== false
);
assert!(
formula
.modify_tree()
.go_down(0)
.add_node(Node::function(
"sin".to_string(),
|inputs| inputs[0].sin(),
Some(1)
))
.is_err()
== false
);
assert!(
formula
.modify_tree()
.go_down(0)
.go_down(1)
.add_node(Node::variable())
.is_err()
== false
);
assert_eq!(formula.as_text(), "sum(X,sin(X))".to_string());
}