bookclub-advr

DSLC Advanced R Book Club
git clone https://git.eamoncaddigan.net/bookclub-advr.git
Log | Files | Refs | README | LICENSE

16-example_accumulator_programming.R (1030B)


      1 
      2 ## STACK EXAMPLE ###### ###### ###### ###### ######
      3 
      4 new_stack <- function(items = list()) {
      5   structure(list(items = items), class = "stack")
      6 }
      7 
      8 push <- function(x, y) {
      9   x$items <- c(x$items, list(y))
     10   x
     11 }
     12 
     13 pop <- function(x) {
     14   n <- length(x$items)
     15   
     16   item <- x$items[[n]]
     17   x$items <- x$items[-n]
     18   
     19   list(item = item, x = x)
     20 }
     21 
     22 s <- new_stack()
     23 s <- push(s, 10)
     24 s <- push(s, 20)
     25 
     26 out <- pop(s)
     27 
     28 out$item
     29 
     30 
     31 ## ZEALLOT EXAMPLE ###### ###### ###### ###### ######
     32 library(zeallot)
     33 
     34 c(value, s) %<-% pop(s)
     35 value
     36 
     37 ###### STACK on R6 ###### ###### ###### ######
     38 Stack <- R6::R6Class("Stack", list(
     39   items = list(),
     40   push = function(x) {
     41     self$items <- c(self$items, x)
     42     invisible(self)
     43   },
     44   pop = function() {
     45     item <- self$items[[self$length()]]
     46     self$items <- self$items[-self$length()]
     47     item
     48   },
     49   length = function() {
     50     length(self$items)
     51   }
     52 ))
     53 
     54 s <- Stack$new()
     55 s$push(10)
     56 s$push(20)
     57 s$pop()
     58 
     59 
     60 ## CHAINING ##### ###### ###### ######
     61 s <- Stack$new()
     62 s$
     63   push(10)$
     64   push(20)$
     65   pop()
     66 
     67 
     68 
     69 
     70 
     71 
     72 
     73 
     74 
     75