Last active
May 12, 2020 10:58
-
-
Save coolbutuseless/6c2ab1b5cc3c9a52d92651eb66dc8d6c to your computer and use it in GitHub Desktop.
defaultlist.R
This file contains hidden or 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
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
#' Create a list with a default value | |
#' | |
#' This behaves exactly like a 'list()' object, except if the requested value | |
#' does not exist, a default value is returned (instead of NULL). | |
#' | |
#' Similar to a `defaultdict` in Python | |
#' | |
#' @param value default value to return if item not in list | |
#' | |
#' @return new `defaultlist` object | |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
defaultlist <- function(value) { | |
structure(list(), class = 'defaultlist', value = value) | |
} | |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
# Fetch value from defaultlist | |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
`[[.defaultlist` <- `$.defaultlist` <- function(x, y) { | |
res <- unclass(x)[[y]] | |
if (is.null(res)) attr(x, 'value') else res | |
} | |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
# Print like a list | |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
print.defaultlist <- function(x, ...) { | |
attr(x, 'value') <- NULL | |
attr(x, 'class') <- NULL | |
print(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment