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@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.