不使用<<-赋值的递归函数? [英] Recursive function without use of <<- assignment?

查看:58
本文介绍了不使用<<-赋值的递归函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个向量 x,我需要在一个内部函数中递归地改变它.这里是我使用 <<- 全局赋值运算符的实现:

Having a vector x, I need to change it recursively in an inner function. Here My implementation of this where I ma using <<- global assignment operator:

 outer <- function(){
  x <- rep(1,5)
  inner <- function(i){
    if(i> length(x))return(x)
    x[i] <<- 2  ## don't work with <-
    inner(i+1)
  }
  inner(1)
}
outer()
[1] 2 2 2 2 2

我的问题是是否有另一个/更好的实现可以避免使用 <<-?请注意,我不想替换 recursion ,只是想问问是否有更好/更安全的设计?

My question if there is another/better implementation that avoid the use of <<-? Note that I don't want to replace recursion , but just to ask if there is better/safer design?

推荐答案

Pass x 作为参数?

Pass x as a parameter?

outer <- function(){
  x <- rep(1,5)
  inner <- function(i,x){
    if(i> length(x))return(x)
    x[i] <- 2  
    inner(i+1,x)
  }
  inner(1,x)
}
outer()
#[1] 2 2 2 2 2

这篇关于不使用&lt;&lt;-赋值的递归函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆