[R] Stack type
Duncan Murdoch
murdoch at stats.uwo.ca
Tue Mar 2 02:14:20 CET 2010
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
More information about the R-help
mailing list