[R] Recall for parent

Gabor Grothendieck ggrothendieck at gmail.com
Thu Mar 30 17:40:07 CEST 2006


On 3/30/06, Thomas Lumley <tlumley at u.washington.edu> wrote:
> On Wed, 29 Mar 2006, Paul Roebuck wrote:
>
> > What's the best way to simulate Recall for parent function?
> > Consider this one-time recursive code:
> >
> > alwaysEven <- function(x) {
> >    handleOdd <- function(x) {
> >        alwaysEven(x-1)    # use Recall-like here
> >    }
> >
> >    return(if (x %% 2) handleOdd(x) else x)
> > }
> > any2even <- alwaysEven
> > rm(alwaysEven)
> > any2even(3)
>
> You can make anonymous recursive functions with local()
>
> whatever <- local({
>               alwaysEven <- function(x) {
>                  handleOdd <- function(x) {
>                     alwaysEven(x-1)
>               }
>               return(if (x %% 2) handleOdd(x) else x)
>               }
>           alwaysEven
>           })
>

Or perhaps this variation which separates the definition and the call:

alwaysEven <- local(alwaysEven <- function(x) {
                  handleOdd <- function(x) {
                     alwaysEven(x-1)
               }
               return(if (x %% 2) handleOdd(x) else x)
               }
)
alwaysEven2 <- alwaysEven
rm(alwaysEven)
alwaysEven2(3)




More information about the R-help mailing list