[R] Stack type
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Mar 2 14:33:43 CET 2010
Here is an example using proto based on converting Duncan's example:
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
On Mon, Mar 1, 2010 at 8:14 PM, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> On 01/03/2010 7:56 PM, Worik R wrote:
>>
>> How can I implement a stack in R?
>>
>> I want to push and pop. Every thing I push and pop will be the same
>> type, but not necessarily an atomic type.
>
> Use lexical scoping:
>
> stack <- function() {
> store <- list()
> push <- function(item) {
> store <<- c(list(item), store)
> invisible(length(store))
> }
> pop <- function() {
> if (!length(store)) stop("Nothing to pop!")
> result <- store[[1]]
> store[[1]] <<- NULL
> result
> }
> list(push=push, pop=pop)
> }
>
> mystack <- stack()
> mystack$push( 1 )
> mystack$push( letters )
> mystack$pop()
> mystack$pop()
> mystack$pop() # gives an error
>
> Duncan Murdoch
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list