abacus v0.4.0 Abacus

A math-expression parser, evaluator and formatter for Elixir.

Features

Supported operators

  • +, -, /, *
  • Exponentials with ^
  • Factorial (n!)
  • Bitwise operators
  • << >> bitshift
  • & bitwise and
  • | bitwise or
  • |^ bitwise xor
  • ~ bitwise not (unary)
  • Boolean operators
  • &&, ||, not
  • ==, !=, >, >=, <, <=
  • Ternary condition ? if_true : if_false

Supported functions

  • sin(x), cos(x), tan(x)
  • round(n, precision = 0), ceil(n, precision = 0), floor(n, precision = 0)

Reserved words

  • true
  • false
  • null

Access to variables in scope

  • a with scope %{"a" => 10} would evaluate to 10
  • a.b with scope %{"a" => %{"b" => 42}} would evaluate to 42
  • list[2] with scope %{"list" => [1, 2, 3]} would evaluate to 3

Data types

  • Boolean: true, false
  • None: null
  • Integer: 0, 40, -184
  • Float: 0.2, 12., .12
  • String: "Hello World", "He said: "Let's write a math parser""

If a variable is not in the scope, eval/2 will result in {:error, error}.

Summary

Functions

Evaluates the given expression with no scope

Evaluates the given expression

Evaluates the given expression with the given scope

Pretty-prints the given expression

Parses the given expr to a syntax tree

Functions

eval(expr)

Specs

eval(expr :: tuple | charlist | String.t) ::
  {:ok, result :: number} |
  {:error, error :: map}

Evaluates the given expression with no scope.

If expr is a string, it will be parsed first.

eval(expr, scope)

Specs

eval(expr :: tuple | charlist | String.t, scope :: map) ::
  {:ok, result :: number} |
  {:error, error :: map}
eval!(expr)

Specs

eval!(expr :: tuple | charlist | String.t) :: result :: number

Evaluates the given expression.

Raises errors when parsing or evaluating goes wrong.

eval!(expr, scope)

Specs

eval!(expr :: tuple | charlist | String.t, scope :: map) :: result :: number

Evaluates the given expression with the given scope.

If expr is a string, it will be parsed first.

format(expr)

Specs

format(expr :: tuple | String.t | charlist) ::
  {:ok, String.t} |
  {:error, error :: map}

Pretty-prints the given expression.

If expr is a string, it will be parsed first.

parse(expr)

Specs

parse(expr :: String.t | charlist) ::
  {:ok, expr :: tuple} |
  {:error, error :: map}

Parses the given expr to a syntax tree.

variables(expr)