Expand description

num_parser: a math interpreter and evaluator

crate license docs

num_parser allows you to easily parse strings into math expressions and evaluate them.

Features

  • Binary and unary operators
  • Supports multiple value types:
    • Bool,
    • Int,
    • Float,
    • Complex,
    • Vector
  • Built-in functions
  • Built-in constants
  • User-defined functions: f(x,y) = xsin(y)+ysin(x)
  • User-defined var: a = pi/2 or b = a+2
  • Define you own functions with macros.
  • Understands ambiguous syntax, like: g(x) = pisinx
  • Recursion: f(x) = branch(x<=2, 1, f(x-1)+f(x-2))
  • Serde support
  • No panicking

Much more will be implemented in future releases!

Use Guide

Evaluating simple static expressions:

use num_parser::*;

assert_eq!(eval("2+2").unwrap(), Value::from(4));
assert_eq!(eval("sin(pi)").unwrap(), Value::from(0));
assert_eq!(eval("re(10+3i)").unwrap(), Value::from(10));

Using contexts:

use num_parser::*;

let mut context = Context::default();
// Declaring a function
let res = eval_with_mutable_context(
    "f(x) = branch(x<=2, 1, f(x-1) + f(x-2))",
    &mut context
).unwrap();

// Result is None
assert_eq!(res, None);
// Calling the function. We could just use eval_with_static_context at this point
let res = eval_with_mutable_context("f(10)", &mut context).unwrap();

assert_eq!(res, Some(Value::from(55)));

Values

Values are contained inside the Value enum, which provides useful functions to access the contained data:

use num_parser::Value;

let value = Value::Float(1.0);

assert_eq!(value.as_bool().unwrap(), true);
assert_eq!(value.as_int().unwrap(), 1);
assert_eq!(value.as_float().unwrap(), 1.0);
assert_eq!(value.as_complex().unwrap(), num::complex::Complex::new(1.0, 0.0));
assert_eq!(value.as_vector(), vec![Value::Float(1.0)]);

// Assign type implicitly:
let implicit = Value::from(1.0);

assert_eq!(value, implicit);

Note that, even thought the initial value was a float, it has been cast into ints and bools. This was possible since the value had no decimal part and it was a one. If these conditions were not met, the cast would have failed.

Operators

Binary operators:

OperatorDescriptionPrecedence
^Exponentiation90
/Division70
*Multiplication70
%Modulo70
+Sum60
-Subtraction60
<Less than50
>Greater than50
<=Less or equal to50
>=Greater or equal to50
==Equal to40
!=Not equal to40
&&Logical AND30
||Logical OR20
,Aggregation. Creates vectors10
=Assignment. Used for functions and vars declarations0

Unary operators:

OperatorDescriptionPrecedence
!Logical NOT80
-Negation60

Functions

FunctionParameters AmountDescription
min>=1Returns the minimum value.
max>=1Returns the maximum value.
floor1Returns the greatest lower integer.
ceil1Returns the lowest greater integer.
round1Returns the rounded integer.
ln1Returns the natural log of the number.
log2 (base, arg)Returns the logarithm of the number with the specified base.
exp1Returns e^(arg).
abs1Returns the absolute value of a number.
sqrt1Returns the square root of a number.
rand2 (min, max)Returns a random float between the two number specified.
branch3 (condition, true, false)Returns the second argument if the condition is true, the third if it is false.
sin1Returns the sine of the angle.
cos1Returns the cosine of the angle.
tan1Returns the tangent of the angle.
asin1Returns the arcsine of the angle.
acos1Returns the arccosine of the angle.
atan1Returns the arctangent of the angle.
sinh1Returns the hyperbolic sine of the angle.
cosh1Returns the hyperbolic cosine of the angle.
tanh1Returns the hyperbolic tangent of the angle.
asinh1Returns the hyperbolic arcsine of the angle.
acosh1Returns the hyperbolic arccosine of the angle.
atanh1Returns the hyperbolic arctangent of the angle.
re1Returns the natural part of the number.
im1Returns the imaginary part of the number.
polar1Returns the polar form (r, theta) of the complex number.
arg1Returns the principal arg of the number.
norm1Returns the length of the vector (re, im).

Context

Contexts allows you keep track of user-defined functions and variables, as well as settings. They can be created as follows:

use num_parser::*;

// Generate the default context
let mut default = Context::default();

// Generate a custom context
let mut custom = Context::new(
    settings::Rounding::NoRounding,
    settings::AngleUnit::Degree,
    settings::DepthLimit::NoLimit
);

Serde

You can use the optional feature serde_support to let all the public structs derive Serialize and Deserialize.

[dependencies]
num = { version = "<version>", features = [ "serde_support" ] }

License and contribution

num_parser is licensed under a MIT License.

Feel free to open issues and pull requests for any problems or ideas you come up with.

Modules

Contains everything you need to create your own built-in function.

Contains contexts settings.

Macros

Creates a Function object from an actual function and an Arguments object.

Given a function name, a FunctionType, a predicate and a target ValueType declares a function. It generates a wrapper that handles types and unbox parameters.

Given a Value of type ValueType::VectorType it declares variables with the provided names.

Structs

Contains user-defined functions and constants.

Enums

Contains all possible error messages. Implements Display.

Every expression variant.

Represent every possible output value.

Contains all possible values types.

Functions

Evaluate an expression with the default context.

Evaluate an expression or add a declaration to the provided context.

Evaluate an expression not allowing context changes.

Type Definitions

A type alias for Result<T, ErrorType>