您好我正在尝试将以下递归伪代码定义转换为 R 中的函数式编程构造:
a = [ random numbers between 0 and 10 ]
b = [ random numbers between -5 and 5 ]
c = [ random numbers between 0 and -10 ]
x0 = 200
index = 0
function f(x) {
index = index + 1
if( x is between 200 and 220 ) return f(x + a[index])
else if(x is between 220 and 250) return f(x + b[index])
else if(x is 250 and above) return f(x + c[index])
}
可执行的R代码是:
a <- sample(1:10,size=50, replace=TRUE)
b <- sample(-5:5,size=50, replace=TRUE)
c <- sample(-1:-10,size=50, replace=TRUE)
index <- 0;
myfunc <- function(x){
index <<- index + 1;
if(index == 50) return(x)
if(x <= 220){ return(myfunc(x + a[index])) }
else if(x > 220 & x < 250){ return(myfunc(x + b[index])) }
else {return( myfunc(x + c[index]))}
}
print(myfunc(200));
想讨论任何方法,包括 Map/Filter/Reduce 或 Vectorisation。提前谢谢了。
此外,我怎样才能保留 50 个 x 元素的整个路径(而不是只看 x 的一个答案)。