1.4 Option Values
(require rebellion/base/option) | package: rebellion |
An option is an optional value that is either present or absent. Present values are constructed with the present function, and absent values are represented by the absent constant.
(define (hash-ref-option h k) (if (hash-has-key? h k) (present (hash-ref h k)) absent))
> (hash-ref-option (hash 'a 1 'b 2) 'a) (present 1)
> (hash-ref-option (hash 'a 1 'b 2) 'c) #<absent>
procedure
(present-value pres) → any/c
pres : present?
procedure
(falsey->option falsey-value) → option?
falsey-value : any/c
> (falsey->option 5) (present 5)
> (falsey->option #false) #<absent>
Note that there is no specialized option->falsey function. In order to convert from an option to a falsey value, use option-get with #false as the default value.
procedure
(option-case opt #:present present-handler #:absent absent-handler) → any/c opt : option? present-handler : (-> any/c any/c) absent-handler : (-> any/c)
> (option-case (present 42) #:present add1 #:absent (λ () (error "missing!"))) 43
> (option-case absent #:present add1 #:absent (λ () (error "missing!"))) missing!
> (option-map (present 42) add1) (present 43)
> (option-map absent add1) #<absent>
(define (inverse x) (if (zero? x) absent (present (/ 1 x))))
> (option-flat-map (present 42) inverse) (present 1/42)
> (option-flat-map absent inverse) #<absent>
> (option-flat-map (present 0) inverse) #<absent>
procedure
(option-filter opt pred) → option?
opt : option? pred : predicate/c
> (option-filter (present 42) number?) (present 42)
> (option-filter (present "hello") number?) #<absent>
> (option-filter absent number?) #<absent>
> (option-or (present 1) (present 2) (present 3)) (present 1)
> (option-or absent (present 2) (present 3)) (present 2)
procedure
(option-or-call first-opt opt-thunk ...) → option?
first-opt : option? opt-thunk : (-> option?)
> (option-or-call absent (λ () (printf "Calling first thunk...") absent) (λ () (printf "Calling second thunk...") (present 1)) (λ () (printf "Calling third thunk...") (present 2))) Calling first thunk...Calling second thunk...
(present 1)
procedure
(option-get opt default) → any/c
opt : option? default : any/c
> (option-get (present 42) 0) 42
> (option-get absent 0) 0
procedure
(in-option opt) → (sequence/c any/c)
opt : option?
1.4.1 Contracts for Option Values
procedure
(option/c contract) → chaperone-contract?
contract : chaperone-contract?
procedure
(present/c contract) → chaperone-contract?
contract : chaperone-contract?