Elex.Context (Elex v0.2.2)
View SourceHolds 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 toElex.Variablestructs:functions- Map of{name, arity}or{name, :variadic}tuples to modules implementingElex.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
@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() }
@type t() :: %Elex.Context{ functions: %{ optional({String.t(), non_neg_integer() | :variadic}) => module() }, variables: %{optional(String.t()) => Elex.Variable.t()} }
Functions
Registers a function module on the context.
Parameters
ctx- The context to updatefunmod- A module implementingElex.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)
@spec add_variable(t(), String.t(), Elex.Variable.t()) :: t()
Adds a variable to the context.
Parameters
ctx- The context to updatename- Variable name as used in expressions (e.g."x")var- AElex.Variablestruct 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)
@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},
# ...
# ]