Home

Awesome

expr

expr is an Elixir library for parsing and evaluating mathematical expressions.

Installation

Add Expr to your mix.exs dependencies:

def deps do
  [{:expr, "~> 0.1.0"}]
end

Afterwards, run the command mix deps.get and you're good to go.

Examples

Operators and constants
OperatorPrecedenceAssociativity
log104RIGHT
floor4RIGHT
ceil4RIGHT
asin4RIGHT
acos4RIGHT
atan4RIGHT
sqrt4RIGHT
log4RIGHT
tan4RIGHT
cos4RIGHT
sin4RIGHT
abs4RIGHT
!4RIGHT
#4RIGHT
^4RIGHT
/3LEFT
*3LEFT
+2LEFT
-2LEFT
<br>
SymbolValue
pi3.14 ...
e2.71 ...
Basic examples

The result of all evaluations are returned at the front of a list. As of version 0.1.0 there is no error checking or expression validation. If something goes wrong, an arithmetic error will be thrown. While the parser will understand your intent for most expressions, the more explicit you are, the better. (Be liberal with parenthesis if you're getting unexpected results!)

Expr.eval!("1 + 2 * 3")
=> [7.0]

Expr.eval!("5/2")
=> [2.5]

Expr.eval!("5! + abs(-5)")
=> [125.0]

Expr.eval!("--4") #Negation
=> [4.0]

Expr.eval!("5(sqrt(abs(-16)))") #Implicit multiplication
=> [20.0]

Expr.eval!("(5^2)(floor(2.75))") #Implicit multiplication #2
=> [50.0]

Expr.eval!("sin(60)") #RADIANS!
=> [-0.3048106211022167]
Variable usage

Valid variable names cannot contain operator names, constant names or start with numbers. Starting with capital letters, containing numbers and unused symbols are fine. However, I recommend using short, lowercase variable names. A map of variable names and their values are passed to Expr.eval! along with an expression when evaluating expressions that contain variables.

Expr.eval!("x + y / x", %{"x" => 2, "y" => 4})
=> [3.0]

Expr.eval!("-x@ + 1", %{"x@" => 2})
=> [-1.0]

Expr.eval!("-(sqrt(abs(some_var)))", %{"some_var" => -2.5})
=> [-1.5811388300841898]

Expr.eval!("ABC+2^CBA", %{"ABC" => 2, "CBA" => 3})
=> [10.0]

vars = %{"a" => 2.5, "b" => 3, "c" => 0.25, "d" => 10, "z" => 6.5}
Expr.eval!("a^(b+c)-d(z)", vars)
=> [-45.35260266120413]
Caveats

Expr.eval!("pi + 1", %{"pi" => 1}) => 4.141592...

TODO

License

This work is free. You can redistribute it and/or modify it under the
terms of the MIT License. See the LICENSE file for more details.