Unity.Interpreter (Unity v0.6.0)

Copy Markdown View Source

Evaluates ASTs produced by Unity.Parser by building Localize.Unit structs and applying operations via Localize.Unit.Math.

The interpreter maintains an environment map for variable bindings (via let) and a special _ binding for the previous result.

Summary

Functions

Evaluates a parsed AST in the given environment.

Types

env()

@type env() :: %{required(String.t()) => Localize.Unit.t() | number()}

result()

@type result() :: Localize.Unit.t() | number() | {:decomposed, [Localize.Unit.t()]}

Functions

eval(ast, environment \\ %{})

@spec eval(term(), env()) :: {:ok, result(), env()} | {:error, String.t()}

Evaluates a parsed AST in the given environment.

Arguments

  • ast - the AST node from Unity.Parser.

  • environment - a map of variable bindings. Defaults to %{}.

Returns

  • {:ok, result, environment} on success, where result is a Localize.Unit.t() or a number, and environment is the updated variable bindings.

  • {:error, message} on failure.

Examples

iex> {:ok, ast} = Unity.Parser.parse("3 meters to feet")
iex> {:ok, result, _env} = Unity.Interpreter.eval(ast)
iex> result.name
"foot"