bertiqwerty / exmex

Math parser and evaluator in Rust, capable of partial differentiation, allows the use of custom operators.
Apache License 2.0
39 stars 6 forks source link

User defined variables. #39

Closed NatanFreeman closed 1 year ago

NatanFreeman commented 1 year ago

I was wondering if there was an idiomatic may to have variables with user defined values that prissiest between calculations. Similar to how evalexpr handles things.

Theoretical usage:

use exmex::prelude::*;
exmex::parse::<f64>("x=14")?;
let expr = exmex::parse::<f64>("x^2+4*x-3")?;
assert_eq!(expr , 249.0);
bertiqwerty commented 1 year ago

What is your use-case? What do you need that for?

NatanFreeman commented 1 year ago

I wanted to make a simple calculator with user input. Is this library not designed for such a use-case?

bertiqwerty commented 1 year ago

At the moment there is no support for assignment to variables in strings to be parsed. If you really want to use Exmex for your calculator, you currently have to build some logic around Exmex to track the variables yourself. Maybe one could add a method FlatEx::assign that returns a new expression to Exmex with the following behavior.

let expr_1 = exmex::parse::<f64>("x^2+y^2+z^2")?;
// variables x and y are turned into constants
let expr_2 = expr_1.assign("x=2;y=2");
// expr_2 only depends on z, since x and y are fixed.
assert!((expr_2.eval(&[4]) - 16.0).abs() < 1e-12);

where the right hand side of = always needs to be an expression without variables. Then a calculator app (that allows users to assign values to variables) would need to detect whether a user input string is an assignment or something that should be evaluated. But it wouldn't need to parse the assignment.

NatanFreeman commented 1 year ago

I would be able to define = as a binary operator using the MakeOperators trait if it weren't for the fact that make cannot return additional information such as variable assignment.

bertiqwerty commented 1 year ago

Yes. Operators cannot be used for that.

NatanFreeman commented 1 year ago

Are there any plans to change the current behaviour to address this?

bertiqwerty commented 1 year ago

To change what precisely?

NatanFreeman commented 1 year ago

Adding detection for assignment. Is this in scope of the project?

bertiqwerty commented 1 year ago

I have currently no plans. I might put more thought into this.

NatanFreeman commented 1 year ago

I'm closing this issue as the current state of implementing this isn't planned to change. This is a very impressive crate even as it stands. I look forward to seeing how it develops.