asciimath/
lib.rs

1//! A mathematical expression parsing and evaluation library.
2//!
3//! # Evaluating an expression with variables
4//!
5//! `eval` is perfect for cases when you just need to evaluate an expression
6//! once, with a given a set of variables.
7//!
8//! ```
9//! use asciimath::{eval, scope};
10//!
11//! let expression = "(x + y * 4) ^ 3";
12//! let variables = scope! {
13//!    "x" => 8,
14//!    "y" => 12.25
15//! };
16//!
17//! assert_eq!(Ok(185193.0), eval(expression, &variables));
18//! ```
19//!
20//!
21//! # Compiling Expressions for Repeated Evaluation
22//!
23//! The example below demonstrates parsing and evaluation of an expression
24//! with two sets of variables.
25//!
26//! The Scope is passed to the compiler for disambiguation in cases of
27//! implicit multiplication and function calls.
28//!
29//! ```
30//! use asciimath::{compile, scope, Evaluate};
31//!
32//! let scope_one = scope! {
33//!    "x" => 8,
34//!    "y" => 12.25
35//! };
36//! let scope_two = scope! {
37//!    "x" => 3,
38//!    "y" => 0
39//! };
40//! let expression = compile("(x + y * 4) ^ 3", &scope_one).unwrap();
41//!
42//! assert_eq!(Ok(185193.0), expression.eval_with(&scope_one));
43//! assert_eq!(Ok(27.0), expression.eval_with(&scope_two));
44//! ```
45//!
46//! # Custom Functions
47//!
48//! A lot of effort has been put into making custom functions as easy to write
49//! as possible.
50//!
51//! ```
52//! use asciimath::{eval, scope, CustomFn};
53//!
54//! let my_sum: CustomFn = |args| Ok(args.iter().sum());
55//!
56//! let scope = scope! {
57//!   "x" => 1,
58//!   "my_sum" => my_sum,
59//! };
60//!
61//! assert_eq!(Ok(6.0), eval("my_sum(x, 2, 3)", &scope));
62//! ```
63//!
64//! # Builtins
65//!
66//! Functions:
67//! - `cos(x)`
68//! - `tan(x)`
69//! - `max(a,b,c,...)`
70//! - `min(a,b,c,...)`
71//! - `abs(x)`
72//! - `sqrt(x)`
73//! - `cbrt(x)`
74//! - `log(base, x)`
75//! - `log_10(x)`
76//! - `ln(x)`
77//! - `floor(x)`
78//! - `ceil(x)`
79//!
80//! Constants:
81//! - PI
82//! - E (Euler's number)
83//! - INFINITY
84//! - NEG_INFINITY
85
86mod ast;
87pub(crate) mod constants;
88mod error;
89mod lexer;
90mod macros;
91mod parser;
92mod tokens;
93mod util;
94
95pub use crate::{
96    ast::{Evaluate, Scope},
97    constants::CustomFn,
98    error::Error,
99    parser::{compile, eval},
100};