The flifo package

2017-01-14

The flifo package provides a few functions to create and manipulate FIFO (First In First Out), LIFO (Last In First Out), and NINO (Not In or Never Out) stacks in R.

Functions fifo, lifo, and nino are made to create empty stacks. For instance:

# Create an empty LIFO
s <- lifo()
print(s)
#> LIFO stack is empty

is.empty(s)
#> [1] TRUE
is.fifo(s)
#> [1] FALSE
is.lifo(s)
#> [1] TRUE

Then push and pop enable one to add elements to and retrieve elements from the stack, respectively.

# Add values to 's'
push(s, 0.3)
push(s, data.frame(x=1:2, y=2:3))
print(s)
#> LIFO stack: next reachable element is:
#> 
#>   x y
#> 1 1 2
#> 2 2 3
size(s)# in bytes
#> [1] 840

# Retrive the last element inserted
pop(s)
#>   x y
#> 1 1 2
#> 2 2 3
size(s)
#> [1] 48

A maximum number of elements can be specified at the creation of the stack (no limit in the number of elements is the default).

s <- fifo(max_length = 3)
max_length(s)
#> [1] 3

# max_length can be changed
max_length(s) <- 2
push(s, 1)
push(s, 2)
push(s, 3) # generates an error
#> Error in push(s, 3) : '.stack' is full

If an object exists in the current environment e and is pushed into the stack, it disappears from e:

s <- lifo()
x <- 3.14
exists("x")
#> [1] TRUE
push(s, x)
exists("x")
#> [1] FALSE

The nino function creates a stack from which we cannot retrieve anything:

s <- nino()
push(s, "foo")
print(s)
#> NINO stack: no element can be reached
pop(s) # generates an error
#> Error in pop(s) : cannont retrieve elements from a 'nino' stack