1 unstable release

Uses old Rust 2015

0.1.0 Nov 11, 2017

#1797 in Math

26 downloads per month
Used in simple_jazz

MIT license

17KB
431 lines

mex a parser/evaluator for simple mathematical expressions, with no dependencies at all. Currently, it supports only a tiny amount of syntax. Here are some valid expressions:

>> 10
10

>> 10 - 3 * 10
-20

>> π = 3.1415926536
3.1415926536

>> 5 * π
15.707963268

And that's it, for now.

It supports the following operators: +, -, *, /, =.

But it's easy to add more (by editing the source).

The crate can be used as a binary or a library. The binary is a REPL, where you enter single expressions line by line and get the result given back to you. An example of the library is below:

use mex::parser;
use mex::evaluator;
use mex::evaluator::context;
use mex::evaluator::object;

fn main() {
    let input = "2 * x";
    let mut parse = parser::Parser::new(input);

    let mut context = context::Context::new();
    context.set(&String::from("x"), object::Object::Number(13.5));

    match parse.parse() {
        Ok(node) => {
            match evaluator::eval_node_in(node, &mut context) {
                Ok(result) => println!("{}", result),
                Err(err) => println!("eval error: {:?}", err),
            }
        }

        Err(e) => println!("parse error: {:?}", e),
    };
}

In the future, I'd like to add these things:

  • Simple API for simple uses

    • e.g. mex::evaluate("1 + 2")3
  • Functions

    • e.g. f(x, y) = x + y
    • e.g. f(2, 3)5
  • Customisation / options

    • Probably via bitflags
    • Things like which operators are allowed, if you're allowed to define variables, etc...
  • Builtins

    • e.g. π, e, sin(θ)
    • Going back to the last point: builtins should be optional
  • Multiple expressions in one

    • e.g. 5 + {1, 2, 3}6, 7, and 8
    • They would be returned in a hash set, probably
  • Symbolic Expressions

    • e.g. 'x = a + b' (maybe with different delimiters)
    • Can be either equations (i.e. with equals), or just simple expressions
    • where clause
      • e.g. 'a + b' where a = 2, b = 1012
    • solve ... for
      • e.g. solve 'a = x + b' for x'x = a - b'
      • e.g. (solve 'a = x + b' for x) where a = 5, b = 23
      • e.g. solve 'x^2 + 3x + 2' for x(x + 1)(x + 2)
    • Maybe even integration/differentiation

No runtime deps