R:收集递归函数的中间输出
R: Collect intermediate output of recursive function
我有一个递归函数,它使用上一次调用的输出作为下一次调用的输入:
recurse_foo = function(input) {
if(identical(input, character(0))) return(NULL)
else {
uu = get_incremental_output(input) ## <-- interested in collecting this
return(recurse_foo(uu))
}
}
很明显,终端输出不是很有趣,我有兴趣收集中间输出,但我无法想象增长全局列表或任何其他副作用会很优雅(这是唯一的事情我能想到)。
这里还有其他可能有用的抽象吗?
谢谢。
具体例子:
final_countdown = function(input) {
if (input/2 < 1) return(NULL)
else {
uu = input/2 # <-- interested in collecting this
print(uu)
return(final_countdown(uu))
}
}
final_countdown(100)
在这种情况下,我有兴趣收集 print
ed 的 uu
序列。
如果所有中间输出都是同一类型,这是一个解决方案:
final_countdown = function(input) {
if (input/2 < 1) return(NA)
else {
c(input, final_countdown(input/2))
}
}
我有一个递归函数,它使用上一次调用的输出作为下一次调用的输入:
recurse_foo = function(input) {
if(identical(input, character(0))) return(NULL)
else {
uu = get_incremental_output(input) ## <-- interested in collecting this
return(recurse_foo(uu))
}
}
很明显,终端输出不是很有趣,我有兴趣收集中间输出,但我无法想象增长全局列表或任何其他副作用会很优雅(这是唯一的事情我能想到)。
这里还有其他可能有用的抽象吗?
谢谢。
具体例子:
final_countdown = function(input) {
if (input/2 < 1) return(NULL)
else {
uu = input/2 # <-- interested in collecting this
print(uu)
return(final_countdown(uu))
}
}
final_countdown(100)
在这种情况下,我有兴趣收集 print
ed 的 uu
序列。
如果所有中间输出都是同一类型,这是一个解决方案:
final_countdown = function(input) {
if (input/2 < 1) return(NA)
else {
c(input, final_countdown(input/2))
}
}