gleam-lang / gleam-lang/stdlib

Add `result.guard` and `option.guard` functions

Open
#907 4 comments 0 reactions 0 assignees View on GitHub
Dominant language
Gleam
Stars
710
Forks
225
Avg merge
5h 52m
Merged PRs (30d)
3

Description

I propose that there be `result.guard` and `option.guard` functions similar to `bool.guard`. I think these would be useful convenience functions and would provide a consistent api in the standard library. My proposed functions are:

```
fn option.guard(
when requirement: Option(a),
return consequence: b,
otherwise alternative: fn(a) -> b,
) -> b {
case requirement {
Some(o) -> alternative(o)
None -> consequence
}
}
```

```
fn result.guard(
when requirement: Result(a, b),
return consequence: c,
otherwise alternative: fn(a) -> c,
) -> b {
case requirement {
Ok(r) -> alternative(r)
Error(_) -> consequence
}
}
```

```
fn result.guard_map(
when requirement: Result(a, b),
return consequence: fn(b) -> c,
otherwise alternative: fn(a) -> c,
) -> b {
case requirement {
Ok(r) -> alternative(r)
Error(e) -> consequence(e)
}
}
```
These functions would provide a consistent way of using the `use` syntax across `bool`, `result`, and `option` libraries, and allow clearer code when the function you are writing does not itself Return a result. For example:

```
fn handler(req: Request, ctx: Context, maybe_user: Option(User)) -> Response(String) {
let unauthorized_request = Response("Not authorized")
let internal_server_error = Response("Status 400")
use user <- option.guard(maybe_user, unauthorized_request)
let db_res = get_info_from_db(req, ctx)
use db_info <- result.guard(db_res, internal_server_error)
Response("Successful response" <> user.name <> ": " <> db_info.success_message)
}
```
This is a familiar gleam pattern that is available from `result.try`, but works in situations where the function you are writing always returns a Response rather than a Result type.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.