用 R 转换抽象语法树

Sté*_*ent 5 r arithmetic-expressions symbolic-math abstract-syntax-tree

例如,给定一个算术表达式,x + y*z我想将其转换为add(x, multiply(y, z)).

我在这里发现了一个有用的功能:

> getAST <- function(ee) purrr::map_if(as.list(ee), is.call, getAST)
> getAST(quote(x + y*z)) 
[[1]]
`+`

[[2]]
x

[[3]]
[[3]][[1]]
`*`

[[3]][[2]]
y

[[3]][[3]]
z
Run Code Online (Sandbox Code Playgroud)

可以使用它rapply(result, as.character, how = "list")来获取字符而不是符号。

如何从这个 AST 中得到add(x, multiply(y, z))(结果)?当有一些括号时,这会变得更加复杂:

> getAST(quote((x + y) * z)) 
[[1]]
`*`

[[2]]
[[2]][[1]]
`(`

[[2]][[2]]
[[2]][[2]][[1]]
`+`

[[2]][[2]][[2]]
x

[[2]][[2]][[3]]
y



[[3]]
z
Run Code Online (Sandbox Code Playgroud)

我不要求答案必须使用该getAST功能。这只是一种可行的方法。

当然,在我的实际用例中,表达式更长。


这是没有括号时的情况的解决方案(我认为):

getAST <- function(ee) purrr::map_if(as.list(ee), is.call, getAST)

ast <- rapply(getAST(quote(x + y*z)), as.character, how = "list")

convertAST <- function(ast) {
  op <- switch(
    ast[[1]],
    "+" = "add",
    "-" = "subtract",
    "*" = "multiply",
    "/" = "divide"
  )
  left <- ast[[2]]
  right <- ast[[3]]
  if(is.character(left) && is.character(right)) {
    return(sprintf("%s(%s, %s)", op, left, right))
  }
  if(is.character(left)) {
    return(sprintf("%s(%s, %s)", op, left, convertAST(right)))
  }
  if(is.character(right)) {
    return(sprintf("%s(%s, %s)", op, convertAST(left), right))
  }
  return(sprintf("%s(%s, %s)", op, convertAST(left), convertAST(right)))
}

convertAST(ast)
Run Code Online (Sandbox Code Playgroud)

G. *_*eck 3

我们可以像这样使用替代品:

subst <- function(e, sub = list(`+` = "add", 
                                `-` = "minus",
                                `/` = "divide",
                                `*` = "multiply")) {
  sub <- Map(as.name, sub)
  do.call("substitute", list(e, sub))
}

# test
e <- quote(x + (y + 1) * z)
res <- subst(e); res
## add(x, multiply((add(y, 1)), z))

# evaluate test against values
add <- `+`; multiply <- `*`; x <- 1; y <- 2; z <- 3
eval(res)
## [1] 10
Run Code Online (Sandbox Code Playgroud)

如果你想要一个字符串结果那么

deparse1(subst(e))
## [1] "add(x, multiply((add(y, 1)), z))"
Run Code Online (Sandbox Code Playgroud)