R/memento.R

Defines functions new.memento

#' Memento environment.
#'
#' Simple implementation of the 'Memento' design pattern.
#'
#' @param i The number of the state.
#' @param state The state to save.
#'
#' @return Memento environment.
#'
#' @note This is the same code as memento.R in the R package \code{archetypes}.
#' Because a different norm is used in this package (the Frobenius norm), I had to
#' change the original archetypes function, which calls this code. My acknowledgement
#' to the authors and maintainer of \code{archetypes}.
#'
#' @examples
#' \dontrun{
#' m <- new.memento()
#' m$save(i, state)
#' m$states()
#' m$get(i)
#' }
#' @aliases memento
#' @rdname memento
#' @noRd
new.memento <- function() {

  memento <- new.env(parent = emptyenv())

  memento$save <- function(i, state) {
    assign(sprintf('s%s', i), state, envir = memento)
  }

  memento$get <- function(i) {
    if ( i < 0 )
      i <- length(memento$states()) + i - 1

    get(sprintf('s%s', i), envir = memento)
  }

  memento$states <- function() {
    ls(pattern = 's\\d+', envir = memento)
  }


  structure(memento, class = 'memento')
}

Try the adamethods package in your browser

Any scripts or data that you put into this service are public.

adamethods documentation built on Aug. 4, 2020, 5:08 p.m.