Elex.Context (Elex v0.2.1)

View Source

Holds variables and functions available when parsing and evaluating expressions.

A context is required by Elex.Parser and Elex.Evaluator. Use Elex.new_context/0 to create one with standard built-in functions, then add variables and custom functions as needed.

Fields

  • :variables - Map of variable name strings to Elex.Variable structs
  • :functions - Map of {name, arity} or {name, :variadic} tuples to modules implementing Elex.Function

Examples

context =
  %Elex.Context{}
  |> Elex.Context.add_function(MyApp.Functions.Double)
  |> Elex.Context.add_variable("x", %Elex.Variable{value: Decimal.new(10), type: :decimal})

Summary

Functions

Registers a function module on the context.

Adds a variable to the context.

Types

t()

@type t() :: %Elex.Context{
  functions: %{
    optional({String.t(), non_neg_integer() | :variadic}) => module()
  },
  variables: %{optional(String.t()) => Elex.Variable.t()}
}

Functions

add_function(ctx, funmod)

@spec add_function(t(), module()) :: t()

Registers a function module on the context.

Parameters

  • ctx - The context to update
  • funmod - A module implementing Elex.Function

Returns

An updated context with the function registered under its signature/0 name and arity.

Examples

context = Elex.new_context()
|> Elex.Context.add_function(MyApp.Functions.Double)

add_variable(ctx, name, var)

@spec add_variable(t(), String.t(), Elex.Variable.t()) :: t()

Adds a variable to the context.

Parameters

  • ctx - The context to update
  • name - Variable name as used in expressions (e.g. "x")
  • var - A Elex.Variable struct with type and value

Returns

An updated context with the variable registered.

Examples

variable = %Elex.Variable{value: Decimal.new(42), type: :decimal}
Elex.Context.add_variable(Elex.new_context(), "answer", variable)