Learn R Programming

sicher (version 0.1.0)

create_type: Create a Custom Type

Description

Creates a new type object for use in the type checking system. A type consists of a name (for error messages) and a checker function (for validation).

Usage

create_type(name, checker)

Value

An object of class `"sicher_type"` containing:

name

The type name as a character string

check

The checker function

Arguments

name

A single character string representing the type name. This name will be displayed in error messages when type checking fails.

checker

A function that takes a single argument and returns `TRUE` if the value matches the type, `FALSE` otherwise. The checker function should be a predicate (e.g., `is.numeric`, `is.character`).

Details

This is the fundamental building block of the type system. Built-in types like `Integer`, `Double`, and `String` are all created using this function.

The checker function should:

  • Accept a single argument (the value to check)

  • Return `TRUE` if the value is valid for this type

  • Return `FALSE` if the value is invalid

  • Not throw errors (error handling is done by `check_type`)

See Also

check_type for type validation, Scalar for creating scalar type variants, Readonly for creating readonly type variants

Examples

Run this code
# Create a custom positive number
Positive <- create_type("positive", function(x) {
  is.numeric(x) && all(x > 0)
})

# Use it in type annotations
age %:% Positive %<-% 25
try(age <- -5)  # Error: Type error

# Create a custom email type
Email <- create_type("email", function(x) {
  is.character(x) &&
    length(x) == 1 &&
    grepl("^[^@]+@[^@]+\\.[^@]+$", x)
})

user_email %:% Email %<-% "user@example.com"

# Create a type for even integers
EvenInt <- create_type("even_int", function(x) {
  is.integer(x) && all(x %% 2 == 0)
})

value %:% EvenInt %<-% 4L
try(value <- 5L)  # Error: Type error

# Create a type that checks data frame structure
PersonDF <- create_type("person_df", function(x) {
  is.data.frame(x) &&
    all(c("name", "age") %in% names(x)) &&
    is.character(x$name) &&
    is.numeric(x$age)
})

Run the code above in your browser using DataLab