Skip to content

Instantly share code, notes, and snippets.

@TimTaylor
Last active May 12, 2020 11:00
Show Gist options
  • Save TimTaylor/b40461f2e727a681e9d897021987ba88 to your computer and use it in GitHub Desktop.
Save TimTaylor/b40461f2e727a681e9d897021987ba88 to your computer and use it in GitHub Desktop.
attempt at defaultdict in R
library(collections)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#' Create a dict with a default value
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
defaultdict <- function(value) {
structure(dict(), class = c('defaultdict'), value = value)
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Fetch value from defaultdict
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
`[[.defaultdict` <- `$.defaultdict` <- function(x, y) {
class(x) <- 'environment'
tmp = x$get(y, default = attr(x, 'value'))
class(x) <- 'defaultdict'
tmp
}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# set value in defaultdict
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
`[[<-.defaultdict` <- `$<-.defaultdict` <- function(x, y, value,...) {
class(x) <- 'environment'
x$set(y, value)
class(x) <- 'defaultdict'
x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment