Caldyn, dynamic evaluation of mathematical expressions
This crate provide run-time evaluation of mathematical expressions, embedded in strings, containing constants and user-provided variables. This can be used to evaluate user-provided expressions in a larger context.
Documentation
Usage
Add the crate to your Cargo.toml
:
[dependencies]
caldyn = "0.1.0"
The easiest way to use this crate is with the eval
function:
assert_eq!;
The second argument to eval
is a Context
, that can define variables:
use Context;
let mut context = new;
context.set;
assert_eq!;
It is also possible to separate the parsing from the evaluation of an expression
with the Expr
type. This allow to reuse the same expression with different
values for variables.
use ;
let expr = parse.unwrap;
assert_eq!;
let expr = parse.unwrap;
let mut context = new;
context.set;
context.set;
assert_eq!;
context.set;
assert_eq!;
It is also possible to set a callback function to be used when a variable is not found in the context:
use ;
let mut context = new;
context.set_query;
assert_eq!;
// the following line would error with "undefined variable 'd'" message
// eval("d / 2", &context);
Usage as a terminal calculator
You can use the calc
example as your terminal calculator,
installing it with cargo:
cargo install caldyn --example calc
Language definition
The language implemented by caldyn can contain the following elements:
- float literal values:
-12.456
,+0.0045e78
, ...; - left and right parenthesis;
- mathematical operators:
+
for addition,-
for subtraction,*
for multiplication,/
for division and^
for exponentiation (std::f64::powf
); - variables. Variables names are ASCII only, and can start by a letter or
_
, and can contain letters, digits or_
. - function call:
sin(a)
,atan(22.0)
. The following function are accessible, with the same meaning as the correspondingstd::f64
function:sqrt
,cbrt
,sin
,cos
,tan
,asin
,acos
,atan
,sinh
,cosh
,tanh
,asinh
,acosh
,atanh
,floor
,ceil
,abs
,exp
,ln
,log2
,log10
.
Any other symbol is forbidden in the input.
The mathematical operators obey the usual relations of associativity and
precedence, but still carry the floating point properties: addition is not
commutative, NaN
and infinities exist, ...
License and contributions
Caldyn is written by Guillaume Fraux and distributed under either the MIT or the Apache license, at your choice. Contributions are welcome, please open an issue before to discuss your changes !