stackUtilities: Perl-like stack utilities for R.

stackUtilitiesR Documentation

Perl-like stack utilities for R.

Description

You can "pop" data off the end of a vector, one element at a time, with pop(). You can also "push" new data onto the end of the vector with push(). The analogous functions for working at the start of a vector are shift() and unshift(): shift() removes the first element of your vector, and unshift() prepends new elements to your vector.

Usage

push(x, values)

pop(x)

unshift(x, values)

shift(x)

Arguments

x

Object, typically a vector or a list.

values

Object to be added to x.

Details

An important and unusual feature of push(), pop(), shift(), and unshift() is that they modify objects "in place"—that is, even when no explicit assignment is done. For example, pop(x) will return the last value of x, but it will also remove the last value from the x object. The examples illustrate this point.

These functions are adapted from Matt Pettis's code at https://gist.github.com/mpettis/b7bfeff282e3b052684f.

Previous versions of these functions were adapted from Jeffrey A. Ryan's code at http://www.lemnica.com/esotericR/Introducing-Closures/. That code works but is based on the creation of "stack" objects that contain their own environments. One consequence is that changing a copy of a stack object changes the original stack object, and vice versa. Note too that, in Ryan's code, the traditional meanings of shift() and unshift() are reversed: he uses shift() to concatenate objects, unshift() to remove a value from an object.

Value

pop() and shift() will return a scalar, that is, an object of length\NB1. push() and unshift() don't return anything.

Author(s)

Matt Pettis

John G. Bullock

See Also

Thomas Leeper's Gist describes his own implementation of pop() and push() and includes links to six other implementations. Some of these implementations of pop() and push() do not have the modify-in-place characteristic of the corresponding Perl functions. This quality is also absent from the constructor function at https://stackoverflow.com/a/14489296/697473.

Examples

myStack <- 1:3
push(myStack, 4)
myStack  # [1] 1 2 3 4

pop(myStack)    # [1] 4
shift(myStack)  # [1] 1
myStack         # [1] 2 3

unshift(myStack, "hello")
myStack         # [1] "hello" "2" "3"

myList <- list(1, 2, 3)  # list with three elements
push(myList, 4)
myList                   # list with 4 elements
shift(myList)            # returns 1
myList[[1]]              # first element of myList is now 2



jbullock35/Bullock documentation built on April 1, 2022, 6:21 p.m.