Abacus (abacus v2.1.0)

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.

Functions

Link to this function

compile(source)

Link to this function

eval(source, scope \\ [], vars \\ %{})

Evaluates the given expression with no scope.

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

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

Evaluates the given expression.

Raises errors when parsing or evaluating goes wrong.

Link to this function

eval!(expr, scope)

@spec 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.

@spec 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.