[R] push/pop on a stack
Marc Schwartz
mschwartz at medanalytics.com
Tue Feb 25 19:19:05 CET 2003
>-----Original Message-----
>From: r-help-admin at stat.math.ethz.ch
>[mailto:r-help-admin at stat.math.ethz.ch] On Behalf Of Barry Rowlingson
>Sent: Tuesday, February 25, 2003 12:10 PM
>To: David Forrest
>Cc: r-help at stat.math.ethz.ch
>Subject: Re: [R] push/pop on a stack
>
>
>
>> It seems like it wouldn't be difficult, and that someone may have
>> already implemented a set of stack functions, and I wouldn't like
to
>> duplicate it.
>
>Here's a Tuesday evening lash-up. Usage is:
>
> > mystack <- stack() # initialisation
> > push(mystack,value) # stores something on the stack
> > pop(mystack) # returns 'value'
>
>There's a print method that lists the stack. Its simply a list. Stack
>underflow is reported as 'attempt to select less than one
>element'. You
>can push anything on the stack. Almost. I just tried pushing a stack
>object onto the stack, and got infinite recursion, cant think why.
>Anyway, this seems to work for most sensible situations!
>
>
>stack <- function(){
>
> it <- list()
> res <- list(
> push=function(x){
> it[[length(it)+1]] <<- x
> },
> pop=function(){
> val <- it[[length(it)]]
> it <<- it[-length(it)]
> return(val)
> },
> value=function(){
> return(it)
> }
> )
> class(res) <- "stack"
> res
>
>}
>
>print.stack <- function(x,...){
> print(x$value())
>}
>
>push <- function(stack,obj){
> stack$push(obj)
>}
>
>pop <- function(stack){
> stack$pop()
>}
>
>
>Baz
Just as an FYI, if you should elect to implement that function, there
is already a stack() function in base R, so you would want to use a
different name.
See ?stack, which is used to transform data.
Regards,
Marc
More information about the R-help
mailing list