Result
Result module: operations on Result(a, e) = Ok(a) Err(e)
Result is the primary error-handling mechanism. Use it for any operation that can reasonably fail. Panics are reserved for programmer errors (invariant violations).
Functions
Collects a list of Results into a Result of a list. Returns the first Err encountered (stopping there), or Ok with all values, in order, if all are Ok. An empty list gives Ok([]).
Examples
march> Result.collect([Ok(1), Ok(2)])
Ok([1, 2])
march> Result.collect([Ok(1), Err("a"), Err("b")])
Err("a")
march> Result.collect([])
Ok([])Extracts the Ok value, panicking with the given message if Err. Use when you are certain the result is Ok.
The panic message includes the underlying Err value so callers can see why the assumption was violated, not just that it was (Result.expect on Err(<err>): <msg>).
Examples
march> Result.expect(Ok(3), "must parse")
3Applies f (which returns a Result) to the Ok value, flattening the result; an Err input is returned unchanged without calling f. Use it to chain fallible steps.
Examples
march> Result.flat_map(Ok(4), fn x -> if x > 0 do Ok(x - 1) else Err("neg") end)
Ok(3)
march> Result.flat_map(Ok(0), fn x -> if x > 0 do Ok(x - 1) else Err("neg") end)
Err("neg")
march> Result.flat_map(String.to_int("21"), fn n -> Ok(n * 2))
Ok(42)Returns true if the result is Err.
Examples
march> Result.is_err(Err("x"))
true
march> Result.is_err(Ok(1))
falseReturns true if the result is Ok.
Examples
march> Result.is_ok(Ok(1))
true
march> Result.is_ok(Err("x"))
falseApplies f to the Ok value, leaving Err unchanged (f is not called).
Examples
march> Result.map(Ok(2), fn x -> x * 10)
Ok(20)
march> Result.map(Err("e"), fn x -> x * 10)
Err("e")Applies f to the Err value, leaving Ok unchanged. The error type may change.
Examples
march> Result.map_err(Err("e"), fn e -> e ++ "!")
Err("e!")
march> Result.map_err(Ok(1), fn e -> e ++ "!")
Ok(1)Returns f(err) if Err, or the original Ok value (without calling f). Use it to recover from an error or replace it with a different one.
Examples
march> Result.or_else(Err("e"), fn _ -> Ok(0))
Ok(0)
march> Result.or_else(Ok(5), fn _ -> Ok(0))
Ok(5)Converts Result(a, e) to Option(a), discarding the error.
Examples
march> Result.to_option(Ok(1))
Some(1)
march> Result.to_option(Err("x"))
NoneExtracts the Ok value, panicking if Err (the panic message includes the Err value). Prefer unwrap_or or a match when Err is possible.
Examples
march> Result.unwrap(Ok(3))
3Extracts the Err value, panicking if Ok.
Examples
march> Result.unwrap_err(Err("bad"))
"bad"Returns the Ok value, or default if Err (the error is discarded).
Examples
march> Result.unwrap_or(Ok(5), 0)
5
march> Result.unwrap_or(Err("bad"), 0)
0