need unwraps a successful value from a Fallible container (such as Result or Optional), or returns the failure early from the enclosing function.
Syntax
(need ⟨fallible-expr⟩)
Semantics
(need ⟨fallible-expr⟩)is an expression macro that expands to:where(match (split-failure ⟨fallible-expr⟩) ((Ok value) value) ((Err failure) (return failure)))split-failureis the method of theFallible :ftype class (split-failure : (:f :a) -> (Result (:f :b) :a)).- Standard library instances of
Fallible:Optional(Fallible Optional): unwrapsxfrom(Some x), or returnsNonefrom the enclosing function (which must also return an(Optional :b)).(Result :e)(Fallible (Result :e)): unwrapsxfrom(Ok x), or returns(Err e)from the enclosing function (which must return(Result :e :b)with the same error type:e).
- Because
needexpands toreturnon the failure branch, it must appear inside a function (and not inside the right-hand side of adobind<-). needdoes not catch thrown exceptions; usecoalton/result:tryorcatchwhen handling exceptions.
Examples
(coalton-toplevel
;; Early-return propagation on `Result`
(declare parse-and-divide (String * String -> (Result String Integer)))
(define (parse-and-divide num-str den-str)
(let n = (need (coalton/result:opt->result "invalid numerator"
(coalton/string:parse-int num-str))))
(let d = (need (coalton/result:opt->result "invalid denominator"
(coalton/string:parse-int den-str))))
(when (== d 0)
(return (Err "division by zero")))
(Ok (coalton/math:div n d)))
;; Early-return propagation on `Optional`
(declare second-element ((List :a) -> (Optional :a)))
(define (second-element xs)
(let rest = (need (coalton/list:tail xs)))
(coalton/list:head rest)))
Other Notes
- Unlike
donotation (which chains callbacks through>>=),needcompiles to flat conditional branching and an immediatereturn, so it works naturally insideforloops and preserves tail-call optimization inrecloops. - User-defined container types can support
needby implementingFalliblefromcoalton/classes.