gleam/result: Short-circuiting guards #4174
-
In the context of a wisp web application, I found myself repeatedly looking for this function in fn unless(inner: Result(a, b), handler: fn(b) -> c, next: fn(a) -> c) {
case inner {
Ok(v) -> next(v)
Error(e) -> handler(e)
}
} In context, this felt useful for running a number of fallible computations in sequence using Analogously I found myself combining type Error {
Client
Server
}
// ...
{
use y <- result.try(int.parse(y) |> result.replace_error(Client))
use z <- result.try(run_a_query(y) |> result.replace_error(Server))
Ok(pure_infallible_function(z))
} Neither of these things is wholly satisfying to me, and having done them I wonder if I'm fighting against something else that Gleam wants me to do. It doesn't help that I'm trying to analogize in my brain to Haskell patterns but I don't think I precisely understand the comparable situation in Haskell. Are people doing stuff like this in a different way using stuff in |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Hello! Could you give some examples of when you'd use that first function? Thank you. That second block of code looks good and usual. 👍 |
Beta Was this translation helpful? Give feedback.
-
https://gloogle.run/search?q=given.not maybe? Edit: You can also specify else_return and have the return fn in the use block |
Beta Was this translation helpful? Give feedback.
To me that reads as another way to write map_error, which is common and well understood in Gleam. We try not to have multiple ways to do the same thing, and we want to encourage people to have the errors constructed in the auxiliary functions rather than at the call-site where possible, so I don't think this is immediately clearly beneficial.