CreateGrammar {gramEvol} | R Documentation |
Context-free Grammar Object
Description
Creates a context-free grammar object.
Usage
grule(...)
gsrule(...)
gvrule(vec)
CreateGrammar(ruleDef, startSymb)
Arguments
... |
A series of comma separated strings or expressions, for |
vec |
An iterable vector or list. |
ruleDef |
Grammatical rule definition. Either a list of grammar rule objects ( See details. |
startSymb |
The symbol where the generation of a new expression should start.
If not given, the first rule in |
Details
The rule definition is the grammar described in Backus-Naur context-free grammatical format.
The preferred way of defining a grammar is to create a list
simulating BNF format,
which collects several named grammar rule objects (GERule
).
Each name defines the non-terminal symbol, and each rule
in the collection determines the production rule,
i.e., possible sequences that will replace the symbol.
Defining a grammar rule object (GERule
) can take three forms:
1. The first form uses grule
(Grammar Rule), where R expressions are accepted. In the mapping process,
variables are looked up and replaced using the production rules.
2. The second form uses gsrule
(Grammar String Rule) and uses character strings. The input to gsrule
are character string values, where any value surrounded by '<' or '>' is considered as non-terminal symbols and
will be replaced using the rule with the same name in the mapping process. Other symbols are considered terminals. This form allows generation of sequences that are not syntactically valid in R (such as `var op var`
).
3. The third form uses gvrule
(Grammar Vector Rule), where objects within an iterable (vector or list) containing all of the expressions are used as individual rules.
Alternatively, CreateGrammar
can read and parse .bnf text files.
Value
CreateGrammar
returns a grammar
object.
grule
and gsrule
return a GERule
object.
See Also
c
,
GrammarMap
,
GrammaticalEvolution
Examples
# Define a simple grammar in BNF format
# <expr> ::= <var><op><var>
# <op> ::= + | - | *
# <var> ::= A | B
ruleDef <- list(expr = gsrule("<var><op><var>"),
op = gsrule("+", "-", "*"),
var = gsrule("A", "B"))
# print rules
print(ruleDef)
# create and display a vector rule
vectorRule = gvrule(1:5)
print(vectorRule)
# Create a grammar object
grammarDef <- CreateGrammar(ruleDef)
# print grammar object
print(grammarDef)
# Creating the same grammar using R expressions
ruleDef <- list(expr = grule(op(var, var)),
op = grule(`+`, `-`, `*`),
var = grule(A, B))
grammarDef <- CreateGrammar(ruleDef)
print(grammarDef)
# Two rules with commas and assignments, preserved using .()
ruleDef <- list(expr = grule(data.frame(dat)),
dat = grule(.(x = 1, y = 2), .(x = 5, y = 6)))
grammarDef <- CreateGrammar(ruleDef)
print(GrammarMap(c(0), grammarDef))
print(GrammarMap(c(1), grammarDef))