R 递归和函数范围变量的深度赋值
当R 递归和函数范围变量的深度赋值,r,recursion,scope,R,Recursion,Scope,当var这不是递归问题时,为什么深度赋值从递归函数起作用漫游流是使用全局变量在结构上定义的。清理您的工作区并运行get_edges,您将看到错误。是的,完全正确。谢谢。这不是递归问题漫游流是使用全局变量在结构上定义的。清理您的工作区并运行get_edges,您将看到错误。是的,完全正确。谢谢 x = structure(list(flow = list(structure(list(type = "Block", id = "a"), .Names = c("type", "id")), st
var这不是递归问题时,为什么深度赋值从递归函数起作用<代码>漫游流
是使用全局变量在结构上定义的。清理您的工作区并运行get_edges
,您将看到错误。是的,完全正确。谢谢。这不是递归问题<代码>漫游流是使用全局变量在结构上定义的。清理您的工作区并运行get_edges
,您将看到错误。是的,完全正确。谢谢
x = structure(list(flow = list(structure(list(type = "Block", id = "a"), .Names = c("type", "id")), structure(list(type = "Branch", flow = list(structure(list( type = "Block", id = "b"), .Names = c("type", "id")), structure(list( type = "Block", id = "c"), .Names = c("type", "id")))), .Names = c("type", "flow")))), .Names = "flow")
str(x)
# List of 1
# $ flow:List of 2
# ..$ :List of 2
# .. ..$ type: chr "Block"
# .. ..$ id : chr "a"
# ..$ :List of 2
# .. ..$ type: chr "Branch"
# .. ..$ flow:List of 2
# .. .. ..$ :List of 2
# .. .. .. ..$ type: chr "Block"
# .. .. .. ..$ id : chr "b"
# .. .. ..$ :List of 2
# .. .. .. ..$ type: chr "Block"
# .. .. .. ..$ id : chr "c"
# a global container
edges = matrix(NA, ncol = 4, nrow = 4,
dimnames = list(c(), c("parent_id", "child_id", "child_type", "block_id")))
i = 1
uid = 0
walk_flow = function(parent) {
parent_id = uid
for (child in parent) {
uid <<- uid + 1
edges[i, c("parent_id", "child_id")] <<- c(parent_id, uid)
edges[i, "child_type"] <<- child$type
if (child$type == "Block") {
edges[i, "block_id"] <<- child$id
} else if (child$type == "Branch") {
i <<- i + 1
edges[i, "parent_id"] <<- uid
walk_flow(child$flow)
next
}
i <<- i + 1
}
}
walk_flow(x$flow)
edges
# parent_id child_id child_type block_id
# [1,] "0" "1" "Block" "a"
# [2,] "0" "2" "Branch" NA
# [3,] "2" "3" "Block" "b"
# [4,] "2" "4" "Block" "c"
get_edges = function(x) {
edges = matrix(NA, ncol = 4, nrow = 4,
dimnames = list(c(), c("parent_id", "child_id", "child_type", "block_id")))
i = 1
uid = 0
walk_flow(x$flow)
return(edges)
}
get_edges(x)
# Error in `[<-`(`*tmp*`, i, c("parent_id", "child_id"), value = c(5, 6)) :
# subscript out of bounds