# Define a typed function that adds two numbers
add_numbers <- fun(
x = numeric,
y = numeric,
return = numeric,
impl = function(x, y) {
return(x + y)
}
)
# Valid call
print(add_numbers(1, 2)) # [1] 3
# Invalid call (throws error)
try(add_numbers("a", 2))
# Define a typed function with multiple return types
concat_or_add <- fun(
x = c(numeric, character),
y = numeric,
return = c(numeric, character),
impl = function(x, y) {
if (is.numeric(x)) {
return(x + y)
} else {
return(paste(x, y))
}
}
)
# Valid calls
print(concat_or_add(1, 2)) # [1] 3
print(concat_or_add("a", 2)) # [1] "a 2"
Run the code above in your browser using DataLab