Last active
May 12, 2020 11:00
-
-
Save TimTaylor/b40461f2e727a681e9d897021987ba88 to your computer and use it in GitHub Desktop.
attempt at defaultdict in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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