Learn R Programming

sicher (version 0.1.0)

typed_function: Create a type-checked function

Description

Wraps a function with runtime type checking for its parameters and, optionally, its return value. This is the function counterpart to the typed variable operators (`%:%` / `%<-%`), providing a syntax analogous to typed function signatures:


  add <- typed_function(
    function(x, y) x + y,
    params  = list(x = Numeric, y = Numeric),
    .return = Numeric
  )

Usage

typed_function(fn, params = list(), .return = NULL)

Value

A function with the same formals as fn and S3 class

"sicher_typed_function" that:

  • Validates each listed parameter on every call.

  • Validates the return value when .return is specified.

  • Delegates all argument passing to fn unchanged.

Arguments

fn

The function to wrap. Its formals are preserved in the wrapper so callers use the exact same signature.

params

A named list mapping parameter names to their types (e.g. list(x = Numeric, y = String)). Only listed parameters are type-checked on each call; unlisted parameters pass through unchecked. Defaults to an empty list (no parameter checking).

.return

Optional return type. When NULL (the default), the return value is not checked. Accepts any sicher_type or sicher_union.

Examples

Run this code
# 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