savage
savage copied to clipboard
simpler example?
hate to ask something stupid but, how do I use this to solve for h in 4 + 2 * h - 3 / 4 = 32 - 2 * 5
this is the sort of thing that I figured would be a primary typical hello-world example, but the documentation makes it looks like I must supply h and let expression = equation.parse::<Expression>().unwrap();
from the example panics
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: [Simple { span: 19..20, reason: Unexpected,
expected: {Some('=')}, found: Some(' '), label: None }]'
in python's sympy, I would do about this:
>>> from sympy import sympify, solve, Eq, symbols
>>> def solve_equation(equation_str, variable='h'):
... var = symbols(variable)
... lhs_str, rhs_str = equation_str.split('=')
... lhs_expr = sympify(lhs_str)
... rhs_expr = sympify(rhs_str)
... equation = Eq(lhs_expr, rhs_expr)
... solutions = solve(equation, var)
... return solutions
>>> equation_str = "4 + 2 * h - 3 / 4 = 32 - 2 * 5"
>>> solve_equation(equation_str)
[75/8]
I tried:
let (lhs_eq, rhs_eq) = equation.split_once(" = ").unwrap();
let lhs = lhs_eq.parse::<Expression>().unwrap();
let rhs = rhs_eq.parse::<Expression>().unwrap();
let expression = eq(lhs, rhs);
dbg!(&expression)
let mut context = HashMap::new();
context.insert("h".to_string(), int(1));
let value = match expression.evaluate(context) {
Ok(n) => Some(n.to_string().parse().unwrap()),
_ => None,
};
but it looks like I have to manually refactor the equation to remove the variable.
&expression = Equal(
Quotient(
Sum(
Integer(
4,
),
Product(
Integer(
2,
),
Difference(
Variable(
"h",
),
Integer(
3,
),
),
),
),
Integer(
4,
),
),
Product(
Difference(
Integer(
32,
),
Integer(
2,
),
),
Integer(
5,
),
),
)
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src/part2_solver.rs:64:43