▼ |  | The Typed Racket Reference

1 | Type Reference
2 | Special Form Reference
3 | Libraries Provided With Typed Racket
4 | Utilities
5 | Exploring Types
6 | Typed Racket Syntax Without Type Checking
7 | Typed Regions
8 | Optimization in Typed Racket
9 | Legacy Forms
10 | Compatibility Languages
11 | Experimental Features

On this page:

assert
with-asserts
defined?
index?
typecheck-fail

5.92
top ← prev up next →

### 4`` Utilities

Typed Racket provides some additional utility functions to facilitate typed programming.

> procedure (assert v) → A
> v : (U #f A)
> (assert v p?) → B
> v : A
> p? : (A -> Any : B)

Verifies that the argument satisfies the constraint. If no predicate is provided, simply checks that the value is not #f.

See also the cast form.

Examples:
> > (define: x : (U #f String) (number->string 7))
> > x
> - : (U False String)
> "7"
> > (assert x)
> "7"
> > (define: y : (U String Symbol) "hello")
> > y
> - : (U Symbol String)
> "hello"
> > (assert y string?)
> "hello"
> > (assert y boolean?)
> Assertion #<procedure:boolean?> failed on "hello"

> syntax (with-asserts ([id maybe-pred] ...) body ...+)
> maybe-pred |  | = |  |
> |  | | |  | predicate

Guard the body with assertions. If any of the assertions fail, the program errors. These assertions behave like assert.

> procedure (defined? v) → boolean?
> v : any/c

A predicate for determining if v is not #<undefined>.

> procedure (index? v) → boolean?
> v : any/c

A predicate for the Index type.

> syntax (typecheck-fail orig-stx maybe-msg maybe-id)
> maybe-msg |  | = |  |
> |  | | |  | msg-string
> maybe-id |  | = |  |
> |  | | |  | #:covered-id id

Explicitly produce a type error, with the source location or orig-stx. If msg-string is present, it must be a literal string, it is used as the error message, otherwise the error message "Incomplete case coverage" is used. If id is present and has type T, then the message "missing coverage of T" is added to the error message.

Examples:
> > (define-syntax (cond* stx)
> (syntax-case stx ()
> [(_ x clause ...)
> #`(cond clause ... [else (typecheck-fail #,stx "incomplete coverage"
> #:covered-id x)])]))
> > (define: (f [x : (U String Integer)]) : Boolean
> (cond* x
> [(string? x) #t]
> [(exact-nonnegative-integer? x) #f]))
> Type Checker: Expected Boolean, but got (Syntaxof (List
> 'typecheck-fail-internal (List 'cond* 'x (List (List
> 'string? 'x) True) (List (List 'exact-nonnegative-integer?
> 'x) False)) String 'x))
> in: #%top-interaction

top ← prev up next →