解析“->"R中的赋值运算符 [英] Parsing "->" assignment operator in R
问题描述
我的问题是关于解析 R 语言中的表达式.让我直接进入一个例子:
My question is about parsing expressions in R language. Let me jump right into an example:
fun_text <- c("
0 -> var
f1 <- function()
{
0 -> sum_var
sum_var2 = 0
sum_var3 <- 0
}
(function()
{
0 -> sum_var
sum_var2 = 0
sum_var3 <- 0
})->f2
f3 = function(x)
{
0 -> sum_var
sum_var2 = 0
sum_var3 <- 0
}
")
fun_tree <- parse(text=fun_text)
fun_tree
fun_tree[[1]]
fun_tree[[2]]
fun_tree[[3]]
fun_tree[[4]]
之后,我们得到这些结果:
After that, we obtain those results:
expression(0 -> var, f1 <- function()
{
0 -> sum_var
sum_var2 = 0
sum_var3 <- 0
}, (function()
{
0 -> sum_var
sum_var2 = 0
sum_var3 <- 0
})->f2, f3 = function(x)
{
0 -> sum_var
sum_var2 = 0
sum_var3 <- 0
})
和
var <- 0
和
f1 <- function() {
sum_var <- 0
sum_var2 = 0
sum_var3 <- 0
}
和
f2 <- (function() {
sum_var <- 0
sum_var2 = 0
sum_var3 <- 0
})
和
f3 = function(x) {
sum_var <- 0
sum_var2 = 0
sum_var3 <- 0
}
如您所见,所有->"赋值运算符都更改为<-",但在第一个示例中并非如此(仅fun_tree").我的问题是:为什么会这样?并且我可以确定我总是在语法树中得到<-"运算符,这样我就可以不用费心去实现->"的情况?
As you can see, all "->" assignment operators are changed to "<-", but not in the first example ("fun_tree" only). My question is: why is that? and can I be sure that I always get "<-" operator in syntax tree, so I can do not bother myself in implementing "->" case?
推荐答案
我可以确定我总是在语法树中得到<-"运算符
can I be sure that I always get "<-" operator in syntax tree
让我们看看……
> quote(b -> a)
a <- b
> identical(quote(b -> a), quote(a <- b))
[1] TRUE
所以是的,->
赋值总是被解析为 <-
(在调用 时同样not->
作为函数名!1).
So yes, the ->
assignment is always parsed as <-
(the same is not true when invoking ->
as a function name!1).
由于 ,您的第一个显示是相反的解析
的keep.source
参数:
Your first display is the other way round because of parse
’s keep.source
argument:
> parse(text = 'b -> a')
expression(b -> a)
> parse(text = 'b -> a', keep.source = FALSE)
expression(a <- b)
<小时>
1 将 <-
作为函数调用与将其作为运算符使用是一样的:
1 Invoking <-
as a function is the same as using it as an operator:
> quote(`<-`(a, b))
a <- b
> identical(quote(a <- b), quote(`<-`(a, b)))
[1] TRUE
但是没有->
函数(虽然可以定义一个),写成b->;a
从不调用 ->
函数,它总是被解析为 a <- b
,反过来,它调用 <-
函数或原语.
However, there is no ->
function (although you can define one), and writing b -> a
never calls a ->
function, it always gets parsed as a <- b
, which, in turn, invokes the <-
function or primitive.
这篇关于解析“->"R中的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!