Learn R Programming

gramEvol (version 2.1-4)

GrammarMap: Sequence to Expression Mapping using Context-free Grammar

Description

Converts a sequence of integer numbers to an expression using a grammar object.

Usage

GrammarMap(inputString, grammar, wrappings = 3, verbose = FALSE)

Arguments

inputString

A vector of integers to define the path of symbol selection in grammar tree. It uses zero-based indexing to address production rules in the grammar.

grammar

A grammar object.

wrappings

The number of times the function is allowed to wrap around inputString if non-terminal symbols are still remaining.

verbose

Prints out each steps of grammar mapping.

Value

A GrammarMap returns a GEPhenotype object.

expr

The generated expression as a character string.

parsed

The generated expression. NULL if the expression still contains non-terminal symbols.

type

"T" if the expression is valid, "NT" if the expression still contains non-terminal symbols.

%% ...

Details

GrammarMap starts from the startExpr defined in the grammar object; then it iterates through inputString, replacing symbols in the expression with associated replacements in the grammar using the current value of inputString.

If the function exhausts all non-terminal symbols in the expression, it terminates. If the end of inputString is reached and still non-terminal symbols exist, the algorithm will restart from the beginning of the current inputString. To avoid unlimited recursions in case of a cyclic grammar, wrappings variable limits the number of this restart.

If verbose = TRUE, step-by-step replacement of symbols with production rules are displayed.

GrammarMap returns a GEPhenotype object, which can be converted to a character string using as.character, or an R expression with as.expression.

See Also

GrammarIsTerminal CreateGrammar, GrammarRandomExpression

Examples

Run this code
# NOT RUN {
# Define a simple grammar
# <expr> ::= <var><op><var>
# <op>   ::= + | - | *
# <var>  ::= A | B | C
ruleDef <- list(expr = gsrule("<var><op><var>"),
                op =   gsrule("+", "-", "*"),
                var =  grule(A, B, C))

# Create a grammar object
grammarDef <- CreateGrammar(ruleDef)

# this should create the expression "A - C"
# <expr>         -> 0 -> <var><op><var>
# <var><op><var> -> 0 -> A<op><var>
# A<op><var>     -> 1 -> A - <var>
# A - <var>      -> 2 -> A - C
sq <- c(0, 0, 1, 2)
expr <- GrammarMap(sq, grammarDef, verbose = TRUE)

print(expr)

# check the expression as a character string
stopifnot(as.character(expr) == "A - C")

# evaluate the expression
A = 5; C = 1
eval(as.expression(expr))
# }

Run the code above in your browser using DataLab