[R] [newbie] stack operations, or functions with side effects (or both)

Tom Roche Tom_Roche at pobox.com
Thu Jan 5 18:18:31 CET 2012


William Dunlap Wed, 4 Jan 2012 22:54:41 +0000
> R functions [can] use their enclosing environments to save state.

Aha!

> makeStack <- function () {
>   stack <- list()
>   list(pop = function() {
>     if (length(stack) == 0) { # get from an enclosing env.
>       retval <- NULL
>     } else {
>       retval <- stack[[length(stack)]] # get from an enclosing env.
>       stack <<- stack[-length(stack)] # assign in an enclosing env.
>     }
>     retval
>   }, push = function(x) {
>     stack[[length(stack) + 1]] <<- x # assign in an enclosing env.
>     invisible(x)
>   })
> }

Thanks, that's quite clear.

> There are various encapsulations of this method in R. See, e.g.,
> "reference classes" or the "proto" package.

I can't see a reference-class implementation, but I did find

https://stat.ethz.ch/pipermail/r-help/2010-March/230353.html (slightly edited)
> [Subject:] [R] Stack type
> [From:] Gabor Grothendieck ggrothendieck at gmail.com
> [Date:] Tue Mar 2 14:33:43 CET 2010

> library(proto)
> Stack <- proto(new = function(.) proto(Stack,
>   stack = NULL,
>   push = function(., el) { .$stack <- c(list(el), .$stack) },
>   pop = function(.) { 
      stopifnot(length(.$stack) > 0)
>     out <- .$stack[[1]]
>     .$stack[[1]] <- NULL
>     out
> }))

> mystack <- Stack$new()
> mystack$push( 1 )
> mystack$push( letters )
> mystack$pop()
> mystack$pop()
> mystack$pop() # gives an error

Thanks again! Tom Roche <Tom_Roche at pobox.com>



More information about the R-help mailing list