Skip to content

Add result.guard and option.guard functionsΒ #907

@chuckberrypi

Description

@chuckberrypi

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions