Parsing operator "->" in R
My question is parsing expressions in R. Let me go straight to 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 get the following 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 }) and
var <- 0 and
f1 <- function() { sum_var <- 0 sum_var2 = 0 sum_var3 <- 0 } and
f2 <- (function() { sum_var <- 0 sum_var2 = 0 sum_var3 <- 0 }) and
f3 = function(x) { sum_var <- 0 sum_var2 = 0 sum_var3 <- 0 } As you can see, all the assignment operators "->" change to "<-", but not in the first example (only "fun_tree"). My question is why? and can I be sure that I always get the "<-" operator in the syntax tree, so I can not bother with the implementation of the "->" case?
Is it possible to be sure that I always get the <- "operator in the syntax tree
Let's see...
> quote(b -> a) a <- b > identical(quote(b -> a), quote(a <- b)) [1] TRUE So, the destination -> always parsed as <- (the same is not true when calling -> as the name of a function! 1 ).
Your first display looks the other way around: parse s keep.source argument :
> parse(text = 'b -> a') expression(b -> a) > parse(text = 'b -> a', keep.source = FALSE) expression(a <- b) 1 Call <- as a function is similar to using as an operator:
> quote(`<-`(a, b)) a <- b > identical(quote(a <- b), quote(`<-`(a, b))) [1] TRUE However, there is no function -> (although you can define it), and writing b -> a never calls the function -> , it is always parsed as a <- b , which, in turn, calls a <- or primitive.