2013-08-11 3 views
-1

R에서 의사 코드를 변환하면 함수 바인딩이 정의 된 상태에서 모든 바인딩이 고정됩니다. R에있는 재귀 함수 작성

lastfunction <- function(inputx) {rep(0,length(inputx))} 
i<-1 
while(i<=2){ 
    afunction <- function(inputx) {i*inputx} #freeze all variable used in the body 
    lastfunction <- lastfunction + afunction #and of course the label "afunction" as well 
    i<-i+1 
} 

#then apply to some data 
lastfunction(c(0,1,5,6)) 

나는 환경 보았지만 (환경 중첩?)

+0

당신은 더 적은 R처럼 많이 보이는 무언가에 의사 코드를 다시 작성할 수 있습니까? 당신은 두 가지 기능을 추가하고 있으며, 당신이 원하는 것을 이해하지 못합니다. – Spacedman

+0

그냥 미주에 :'리콜 '을보세요. –

답변

2

만들고 local와 함께 새로운 환경을 사용할 수 있습니다 제대로하는 방법을 볼 수 없습니다.

f <- list() 
for(i in 1:10) { 
    f[[i]] <- local({ 
     j <- i # j is only visible in this local environment, 
       # and it is a different environment at each iteration. 
     function() j 
    }) 
} 
f[[3]]() 
# [1] 3 

은 또한 (function(){ ... })() 대신 local로 기록 될 수 있습니다.

instead of `local({ ... })`. 
f <- list() 
for(i in 1:10) { 
    f[[i]] <- 
    (function(){ 
     j <- i 
     function() j 
    })() 
} 
f[[3]]() 

귀하의 예는 될 :

f <- function(x) rep(0, length(x)) 
for(i in -1:2) { 
    f <- local({ 
    # Copy the variables i and f 
    j <- i 
    g1 <- f 
    g2 <- function(x) j*x 
    # Define the new function 
    function(x) { 
     cat("i=", j, " Adding ", paste0(g2(x),sep=","), "\n", sep="") 
     g1(x) + g2(x) 
    } 
    }) 
} 

# Check that result is correct 
h <- function(x) 2*x 
f(1:3) 
# i=2 Adding 2,4,6, 
# i=1 Adding 1,2,3, 
# i=0 Adding 0,0,0, 
# i=-1 Adding -1,-2,-3, 
# [1] 2 4 6 
h(1:3) 
# [1] 2 4 6