2 Coercion
(require sugar/coerce) | package: sugar |
Functions that coerce the datatype of a value to another type. Racket already has type-specific conversion functions. But if you’re handling values of indeterminate type — as sometimes happens in an untyped language — then handling the possible cases individually gets to be a drag.
2.1 Values
Numbers are rounded down to the nearest integer.
Examples: | ||||||||
|
Stringlike values — paths, symbols, and strings — are converted to numbers and rounded down.
Examples: | ||||||
|
Characters are directly converted to integers.
Examples: | ||||
|
Lists, vectors, and other multi-value datatypes return their length (using len).
Examples: | ||||
|
Example: | ||
|
Examples: | ||||||||||||
|
Examples: | ||||||||||||
|
Examples: | ||||||||||||
|
Note that a string is treated as an atomic value rather than decomposed with string->list. This is done so the function handles strings the same way as symbols and paths.
Examples: | ||||||||||||||
|
Examples: | ||||||||||||||
|
Examples: | ||||||||||
|
procedure
v : any/c
procedure
(stringish? v) → boolean?
v : any/c
procedure
(symbolish? v) → boolean?
v : any/c
procedure
v : any/c
procedure
(complete-pathish? v) → boolean?
v : any/c
procedure
v : any/c
procedure
(vectorish? v) → boolean?
v : any/c
Examples: | ||||||||||||||
|
2.2 Coercion contracts
procedure
(coerce/int? v) → integer?
v : any/c
procedure
(coerce/string? v) → string?
v : any/c
procedure
(coerce/symbol? v) → symbol?
v : any/c
procedure
(coerce/path? v) → path?
v : any/c
procedure
(coerce/boolean? v) → boolean?
v : any/c
Examples: | ||||||||||||||||||
|
Please note: this is not an officially sanctioned way to use Racket’s contract system, because contracts aren’t supposed to mutate their values (see make-contract).
But coercion contracts can be useful in two situations:
You want to be liberal about input types, but don’t want to deal with the housekeeping and manual conversions between types.
Your contract involves an expensive operation that you’d rather avoid performing twice.