Skip to contents

Generate an Arithmetic Expression Parser

Usage

make_expr_parser(parser_name = NULL, finalizer = force)

Arguments

parser_name

Name of the parsing function as a character string. No longer used, but still present for back-compatibility.

finalizer

Function used to post-process a parsed formula. The default is the identity finalizer, which returns the parsed formula itself. Other good choices are finalizer_char, which can be used to understand how the formula has been parsed, and finalizer_index, which can be passed to the C++ engine.

The result of this function is another function that takes a single argument, x. This resulting function is recursive. The x argument should be a one-sided formula the first time this recursive function is called. In subsequent evaluations of the recursion, x will be a list with the following structure. When x is a formula, it must contain a named list of functions called valid_funcs and a named list of variables called valid_vars.

x

list of names and numeric objects that represent each leaf of the parse tree

n

integer vector the same length as x that give the number of arguments of the associated functions in x or 0 otherwise

i

index identifying the element of x corresponding to the first argument of the associated function or 0 if this is not a function

valid_funcs

named list of valid functions that was extracted from the environment of the formula being parsed

valid_vars

named list of default values of valid variables extracted from the environment of the formula being parsed

input_expr_as_string

the input formula stored as a string

Examples

parser = make_expr_parser(finalizer = finalizer_char)
foi = ~ beta * I / 100
valid_funcs = setNames(
  list(`*`, `/`),
  c("*", "/")
)
valid_vars = list(beta = 0.1, I = 30)
parser(foi)
#>      x n i
#> 1    ~ 1 1
#> 2    / 2 2
#> 3    * 2 4
#> 4  100 0 0
#> 5 beta 0 0
#> 6    I 0 0