Elex.Context (Elex v0.2.2)

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.

Returns metadata for every function registered on the context.

Types

function_info()

@type function_info() :: %{
  :module => module(),
  :name => String.t(),
  :arity => non_neg_integer() | :variadic,
  :signature => String.t(),
  :description => String.t(),
  optional(:min_arity) => non_neg_integer(),
  optional(:category) => atom()
}

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)

list_functions(context)

@spec list_functions(t()) :: [function_info()]

Returns metadata for every function registered on the context.

Each entry is a map with :module, :name, :arity, :signature, and :description. Variadic functions use :arity of :variadic and include :min_arity. When a function's documentation/0 callback includes :category, that key is included as well.

The list is sorted by function name.

Examples

context = Elex.new_context()
Elex.Context.list_functions(context)
#=> [
#     %{module: Elex.Functions.Abs, name: "abs", arity: 1,
#       signature: "abs(x)", description: "...", category: :math},
#     ...
#   ]