给定一个算术表达式,例如x + y*z
,我想将其转换为add(x, multiply(y, z))
.
我找到了一个helpful function here:
> 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
你可以用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
我不要求答案一定要用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)