Runtime evaluation: Difference between revisions

→‎{{header|R}}: implemented R version
(→‎{{header|R}}: implemented R version)
Line 437:
'[http://software-lab.de/doc/refL.html#let let]' or
'[http://software-lab.de/doc/refJ.html#job job]'.
 
{{header|R}}
 
In R, expressions may be manipulated directly as abstract syntax trees, and evaluated within environments.
 
<tt>quote()</tt> captures the abstract syntax tree of an expression.
<tt>parse()</tt> does the same starting from a string.
<tt>call()</tt> constructs an evaluable parse tree.
Thus all these three are equivalent.
 
<lang r>expr1 <- quote(a+b*c)
expr2 <- parse(text="a+b*c")[[1]]
expr3 <- call("+", quote(`a`), call("*", quote(`b`), quote(`c`)))</lang>
 
<tt>eval()</tt> evaluates a quoted expression. <tt>evalq()</tt> is a version of <tt>eval()</tt> which quotes its first argument.
 
<lang r>> a <- 1; b <- 2; c <- 3
> eval(expr1)
[1] 7</lang>
 
<tt>eval()</tt> has an optional second environment which is the lexical environment to evaluate in.
 
<lang r>> env <- as.environment(list(a=1, b=3, c=2))
> evalq(a, env)
[1] 1
> eval(expr1, env) #this fails; env has only emptyenv() as a parent so can't find "+"
Error in eval(expr, envir, enclos) : could not find function "+"
> parent.env(env) <- sys.frame()
> eval(expr1, env) # eval in env, enclosed in the current context
[1] 7
> assign("b", 5, env) # assign() can assign into environments
> eval(expr1, env)
[1] 11</lang>
 
=={{header|Ruby}}==
Anonymous user