need is a macro that takes the value held by a Result or Optional, or
returns its failure from the enclosing function.
Syntax
(need ⟨expr⟩)
Semantics
⟨expr⟩must have a type that is an instance of theFallibleclass, such as(Result :e :a)or(Optional :a).- If
⟨expr⟩holds a value, such as(Ok x)or(Some x), theneedexpression evaluates to that value. - Otherwise
needreturns the failure, such as(Err e)orNone, from the nearest enclosing function, likereturn. That function must therefore return aResultwith the same error type, or anOptional. needdoes not catch exceptions. Usecoalton/result:tryto turn a thrown exception into aResultfirst.(need ⟨expr⟩)expands to(match (split-failure ⟨expr⟩) ((Ok v) v) ((Err f) (return f))), wheresplit-failureis the method ofFallible. Becauseneedis a macro, it is not itself a function.
Example
(declare add-parsed (String * String -> (Result String Integer)))
(define (add-parsed a b)
(let x = (need (parse-number a)))
(let y = (need (parse-number b)))
(Ok (+ x y)))