1.8 Variants
(require rebellion/base/variant) | package: rebellion |
A variant is a value tagged with a keyword. Variants are used to distinguish different kinds of values by name, without knowing anything about the types of those values.
> (variant #:success 42) (variant #:success 42)
> (variant #:failure "oops") (variant #:failure "oops")
Additionally, the variant constructor may be used as a match expander.
(define (try-add1 v) (match v [(variant #:success x) (add1 x)] [(variant #:failure msg) (error msg)]))
> (try-add1 (variant #:success 42)) 43
> (try-add1 (variant #:failure "oops")) oops
procedure
(variant-value var) → any/c
var : variant?
> (variant-value (variant #:success 42)) 42
> (variant-value (variant #:failure "oops")) "oops"
procedure
(variant-tag var) → keyword?
var : variant?
> (variant-tag (variant #:success 42)) '#:success
> (variant-tag (variant #:failure "oops")) '#:failure
procedure
(variant-tagged-as? var tag-keyword) → boolean?
var : variant? tag-keyword : keyword?
> (variant-tagged-as? (variant #:success 42) '#:success) #t
> (variant-tagged-as? (variant #:success 42) '#:failure) #f
(define/contract (get-success-or-zero var) (-> (variant/c #:success number? #:failure string?) number?) (match var [(variant #:success x) x] [(variant #:failure _) 0]))
> (get-success-or-zero (variant #:success 42)) 42
> (get-success-or-zero (variant #:success "not a number")) get-success-or-zero: contract violation
expected: number?
given: "not a number"
in: the #:success case of
the 1st argument of
(->
(variant/c
#:failure
string?
#:success
number?)
number?)
contract from:
(function get-success-or-zero)
blaming: top-level
(assuming the contract is correct)
at: eval:2.0
> (get-success-or-zero (variant #:other "whoops")) get-success-or-zero: contract violation
expected: a variant with tag #:failure or #:success
given: (variant #:other "whoops")
in: the 1st argument of
(->
(variant/c
#:failure
string?
#:success
number?)
number?)
contract from:
(function get-success-or-zero)
blaming: top-level
(assuming the contract is correct)
at: eval:2.0