# Basic typed function
add <- typed_function(
function(x, y) x + y,
params = list(x = Numeric, y = Numeric),
.return = Numeric
)
add(1, 2) # Returns 3
try(add("a", 2)) # Error: Type error in 'x': Expected numeric, got string
# Optional parameter
greet <- typed_function(
function(name, title = NULL) {
if (is.null(title)) paste("Hello,", name)
else paste("Hello,", title, name)
},
params = list(name = String, title = Optional(String))
)
greet("Alice") # "Hello, Alice"
greet("Alice", title = "Dr.") # "Hello, Dr. Alice"
try(greet("Alice", title = 42)) # Error: Type error in 'title'
# Union type in params
describe <- typed_function(
function(id) paste("ID:", id),
params = list(id = String | Numeric),
.return = String
)
describe("abc") # "ID: abc"
describe(123) # "ID: 123"
try(describe(TRUE)) # Error: Type error in 'id'
Run the code above in your browser using DataLab