Result module
The
gleam/result
standard library module contains functions for working with results. Gleam
programs will make heavy use of this module to avoid excessive nested case
expressions when calling multiple functions that can fail.
map
updates a value held within the Ok of a result by calling a given function on
it. If the result is an error then the function is not called.
try
runs a result-returning function on the value held within an Ok of a result.
If the result is an error then the function is not called. This is useful for
chaining together multiple function calls that can fail, one after the other,
stopping at the first error.
unwrap
extracts the success value from a result, or returning a default value if the
result is an error.
Result functions are often used with pipelines to chain together multiple calls to result-returning functions.
import gleam/int
import gleam/io
import gleam/result
pub fn main() {
io.println("=== map ===")
let _ = io.debug(result.map(Ok(1), fn(x) { x * 2 }))
let _ = io.debug(result.map(Error(1), fn(x) { x * 2 }))
io.println("=== try ===")
let _ = io.debug(result.try(Ok("1"), int.parse))
let _ = io.debug(result.try(Ok("no"), int.parse))
let _ = io.debug(result.try(Error(Nil), int.parse))
io.println("=== unwrap ===")
io.debug(result.unwrap(Ok("1234"), "default"))
io.debug(result.unwrap(Error(Nil), "default"))
io.println("=== pipeline ===")
int.parse("-1234")
|> result.map(int.absolute_value)
|> result.try(int.remainder(_, 42))
|> io.debug
}