7.7
2.4 Enum Types
(require rebellion/type/enum) | package: rebellion |
An enum type is a simple kind of data type made up of a small fixed set of named values. Enum types are useful for representing groups of related constants, such as primary colors and directions.
Examples:
(define-enum-type direction (up down left right)) (define-tuple-type point (x y)) (define/contract (point-move pt dir amount) (-> point? direction? real? point?) (define x (point-x pt)) (define y (point-y pt)) (cond [(equal? dir up) (point x (+ y amount))] [(equal? dir down) (point x (- y amount))] [(equal? dir left) (point (- x amount) y)] [(equal? dir right) (point (+ x amount) y)]))
> (point-move (point 2 2) up 5) (point 2 7)
> (point-move (point 1 4) left 10) (point -9 4)
> (point-move (point 1 4) 'up 5) point-move: contract violation
expected: direction?
given: 'up
in: the 2nd argument of
(-> point? direction? real? point?)
contract from: (function point-move)
blaming: top-level
(assuming the contract is correct)
at: eval:4.0
syntax
(define-enum-type id (case-id ...) enum-option ...)
enum-option = #:predicate-name predicate-id | #:property-maker property-maker
property-maker :
(-> uninitialized-singleton-descriptor? (listof (cons/c struct-type-property? any/c)))
Creates an enum type named id. Each case-id is bound
to a constant, and predicate-id is bound to a predicate that returns
#t when given any of the constants and returns #f for all
other values. If #:predicate-name is not given, then predicate-id defaults to id?.
Examples:
> (define-enum-type suit (diamonds clubs hearts spades)) > (suit? diamonds) #t
> (suit? 42) #f
> spades #<suit:spades>