I'm trying to build an object for nested function calls. The idea is to write something based on simple common expressions such as f64 + f64. The Expr object then builds something similar to a parsed mathematical expression by implementing it's own arithmetic operations and acting on its children. Theoretically, one would then call the upper Expr object and it will in turn call its children and so own until an Expr with no children is found and the result can be propagated backwards.
However, I am unable to satisfy the compiler regarding moved objects (The code below doesn't compile)... I would appreciate any help!
use std::ops::Add;
pub struct Expr {
children: (Box<Option<Expr>>, Box<Option<Expr>>), //children expressions
func: Box<dyn Fn(f64, f64) -> f64>, //expr's function
}
impl Add<Expr> for Expr {
type Output = Expr;
fn add(self, rhs: Expr) -> Self::Output {
let children = (Box::new(Some(self)), Box::new(Some(rhs)));
let mut res = Expr {
children,
func: Box::new(|l, r| -> f64 { 1. }), //dummy function to be replaced
};
res.func = Box::new(
|l, r| -> f64 {
(&res.children.0.unwrap().func)(l, r) + (&res.children.1.unwrap().func)(l, r)
}
);
res
}
}