Handler in node
This commit is contained in:
parent
6f0c9cf943
commit
b22dd00177
1 changed files with 28 additions and 11 deletions
|
|
@ -1,37 +1,54 @@
|
||||||
use crate::node::node_modifier::NodeModifier;
|
use crate::node::node_modifier::NodeModifier;
|
||||||
|
use handler::*;
|
||||||
|
|
||||||
|
mod handler;
|
||||||
mod node_modifier;
|
mod node_modifier;
|
||||||
|
|
||||||
pub struct Node {
|
pub struct Node {
|
||||||
children: Vec<Node>,
|
children: Vec<Node>,
|
||||||
function: fn(Vec<f64>) -> f64,
|
handler: Box<dyn NodeHandler>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Node {
|
impl Node {
|
||||||
pub fn new(children: Option<Vec<Node>>, function: Option<fn(Vec<f64>) -> f64>) -> Self {
|
pub fn new<T>(children: Option<Vec<Node>>, handler: T) -> Self
|
||||||
|
where
|
||||||
|
T: NodeHandler + 'static,
|
||||||
|
{
|
||||||
Self {
|
Self {
|
||||||
children: children.unwrap_or(vec![]),
|
children: children.unwrap_or(vec![]),
|
||||||
function: function.unwrap_or(|_| 0f64),
|
handler: Box::new(handler),
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn empty() -> Self {
|
|
||||||
Self {
|
|
||||||
children: vec![],
|
|
||||||
function: |_| 0f64,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn get_value(&self) -> f64 {
|
pub fn get_value(&self) -> f64 {
|
||||||
if self.children.len() == 0 {
|
if self.children.len() == 0 {
|
||||||
return (self.function)(vec![0f64]);
|
return self.handler.run(vec![0f64]);
|
||||||
}
|
}
|
||||||
let mut inputs: Vec<f64> = vec![];
|
let mut inputs: Vec<f64> = vec![];
|
||||||
for node in &self.children {
|
for node in &self.children {
|
||||||
inputs.push(node.get_value());
|
inputs.push(node.get_value());
|
||||||
}
|
}
|
||||||
|
|
||||||
return (self.function)(inputs);
|
return self.handler.run(inputs);
|
||||||
}
|
}
|
||||||
pub fn modify_tree<'a>(&'a mut self) -> NodeModifier<'a> {
|
pub fn modify_tree<'a>(&'a mut self) -> NodeModifier<'a> {
|
||||||
NodeModifier::from_random(self)
|
NodeModifier::from_random(self)
|
||||||
}
|
}
|
||||||
|
pub fn number(n: f64) -> Node {
|
||||||
|
Node {
|
||||||
|
children: vec![],
|
||||||
|
handler: Box::new(NodeNumber::new(Some(n))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn function(func: fn(Vec<f64>) -> f64) -> Node {
|
||||||
|
Node {
|
||||||
|
children: vec![],
|
||||||
|
handler: Box::new(NodeFunction::new(func)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn variable(getter: fn() -> f64) -> Node {
|
||||||
|
Node {
|
||||||
|
children: vec![],
|
||||||
|
handler: Box::new(NodeVariable::new(getter)),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue