RStack {R6DS} | R Documentation |
The RStack reference class
Description
The RStack reference class implements the data structure stack.
Usage
RStack
Format
An object of class R6ClassGenerator
of length 24.
Details
A stack is an ordered list of elements following the Last-In-First-Out (LIFO) principle.
The push
method takes elements and add them to the top position (right) of the stack,
while the pop
method returns and removes the last "pushed" (top or rightmost) element in the stack.
The elements in the stack are not necessarily to be of the same type, and they can be any R objects.
References
For the details about the stack data structure, see Stack at Wikipedia.
Immutable Methods
The immutable method does not change the instance.
peek()
-
This method returns the last pushed (top or rightmost) element in the stack. It returns
NULL
if the stack is empty.
Mutable Methods
The mutable methods change the instance.
push(..., collapse=NULL)
-
The
push
method pushes the elements in...
andcollapse
into the stack (to the top or right).Note that you can input multiple elements.
pop()
-
The
pop
method pops (returns and removes) the last pushed (rightmost) element in the stack. It returnsNULL
if the stack is empty.
Author(s)
Yukai Yang, yukai.yang@statistik.uu.se
See Also
R6DS for the introduction of the reference class and some common methods
Examples
### create a new instance
# to create a new instance of the class
stack <- RStack$new()
# the previous RStack instance will be removed if you run
stack <- RStack$new(0, 1, 2, collapse=list(3, 4))
# the following sentence is equivalent to the above
stack <- RStack$new(0, 1, 2, 3, 4)
# where the numbers 0, 1, 2, 3, 4 are pushed into the stack
### push elements
# it can be one single element
stack$push(5)
# it can be several elements separated by commas
# note the whole list will be one element of the stack
# because it is not passed through the collapse argument
stack$push(list(a=10,b=20), "Hello world!")
# the collapse argument takes a list whose elements will be collapsed
# but the elements' names will not be saved
stack$push(collapse = list(x=100,y=200))
# they can be used together
stack$push("hurrah", collapse = list("RStack",300))
### pop an element
# pop only one element at a time
val <- stack$pop()
# then we keep poping!
while(!is.null(val)) val <- stack$pop()