meval-rs
This Rust crate provides a simple math expression parsing and evaluation. Its main goal is to
be convenient to use, while allowing for some flexibility. Currently works only with f64
types.
Documentation
Installation
Simply add the corresponding entry to your Cargo.toml
dependency list:
[]
= "0.0.5"
and add this to your crate root:
extern crate meval;
Simple examples
extern crate meval;
Need to define a Rust function from an expression? No problem, use Expr
for this and more:
extern crate meval;
Expr::bind
returns a boxed closure that is slightly less
convenient than an unboxed closure since Box<Fn(f64) -> f64>
does not implement FnOnce
,
Fn
or FnMut
. So to use it directly as a function argument where a closure is expected, it
has to be manually dereferenced:
let func = from_str.unwrap.bind.unwrap;
let r = Some.map;
Custom constants and functions? Define a context!
let y = 1.;
let expr = from_str.unwrap;
// create a context with function definitions and variables
let ctx = ;
// bind function with builtins as well as custom context
let func = expr.bind_with_context.unwrap;
assert_eq!;
For functions with 2, 3, and N variables use CustomFunc2
, CustomFunc3
and CustomFuncN
respectively.
If you need a custom function depending on mutable parameters, you will need to use a
Cell
:
use Cell;
let y = new;
let expr = from_str.unwrap;
let ctx = CustomFunc;
let func = expr.bind_with_context.unwrap;
assert_eq!;
y.set;
assert_eq!;
Supported expressions
meval
supports basic mathematical operations on floating point numbers:
- binary operators:
+
,-
,*
,/
,^
(power) - unary operators:
+
,-
It supports custom variables like x
, weight
, C_0
, etc. A variable must start with
[a-zA-Z_]
and can contain only [a-zA-Z0-9_]
.
Build-ins (given by context meval::builtin()
) currently supported:
-
functions implemented using functions of the same name in Rust std library:
sqrt
,abs
exp
,ln
sin
,cos
,tan
,asin
,acos
,atan
,atan2
sinh
,cosh
,tanh
,asinh
,acosh
,atanh
floor
,ceil
,round
signum
-
other functions:
max(x, ...)
,min(x, ...)
: maximum and minimumum of 1 or more numbers
-
constants:
pi
e
Related projects
This is a toy project of mine for learning Rust, and to be hopefully useful when writing command line scripts. For other similar projects see:
License
This project is dual-licensed under the Unlicense and MIT licenses.
You may use this code under the terms of either license.