Description Usage Arguments Details Value Examples
View source: R/match_enum_arg.R
Call this function at the beginning of your own function that uses an enum parameter to validate the passed enum value against the list of allowed enum values.
1 | match.enum.arg(arg, choices)
|
arg |
The actual function parameter that shall be validated against the allowed enum values |
choices |
Optional: The list of allowed enum values. You can omit this parameter if the formal
parameter is declared via |
You can pass an enum value name or the value itself.
If no enum value is passed (missing parameter value) the first item of the enum is used as default value.
Based on the R code of the base function match.arg
.
Inspired by https://stackoverflow.com/questions/33838392/enum-like-arguments-in-r
Returns the passed actual parameter if is a valid enum value. If no actual parameter was passed it returns the first element of the enum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | ColorEnum <- list(BLUE = 1L, RED = 2L, BLACK = 3L)
print_color_code = function(enum = ColorEnum) {
i <- match.enum.arg(enum)
print(i)
invisible(i)
}
print_color_code(ColorEnum$RED) # use a value from the enum (with auto completion support)
# [1] 2
print_color_code() # takes the first color of the ColorEnum
# [1] 1
print_color_code(3) # an integer enum value (dirty, just for demonstration)
# [1] 3
## Not run:
print_color_code(4) # an invalid number
# Error in match.enum.arg(enum) :
# 'arg' must be one of the values in the 'choices' list: BLUE = 1, RED = 2, BLACK = 3
## End(Not run)
PAYMENT_FREQUENCY <- create.enum(c(12, 4, 1), c("MONTHLY", "QUARTERLY", "ANNUALY"))
payment.amount <- function(annual.amount, payment.frequency = PAYMENT_FREQUENCY) {
payments.per.year <- match.enum.arg(payment.frequency)
return(annual.amount / payments.per.year)
}
payment.amount(120, PAYMENT_FREQUENCY$MONTHLY)
# [1] 10
payment.amount(120, PAYMENT_FREQUENCY$QUARTERLY)
# [1] 30
## Not run:
payment.amount(120, 2)
# Error in match.enum.arg(payment.frequency) :
# 'arg' must be one of the values in the 'choices' list: MONTHLY = 12, QUARTERLY = 4, ANNUALY = 1
## End(Not run)
payment.amount(120) # uses the first value as default value!
# [1] 10
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.