Stream: ideas

Topic: backpassing `when`


view this post on Zulip timotree (Aug 02 2023 at 20:46):

It looks like -> is currently used for two things: lambdas and when ... is expressions. Backpassing with <- can currently only be used in place of lambdas. I don't know if the syntax is readable, but it does appeal to my desire for consistency to use the same syntax to avoid indentation with when in cases where all but one pattern should short-circuit the function. Example:

main =
    Found position <- when binarySearch [1, 3, 4] 4 is
        NotFound -> Err "number not found in list"
    # do many lines of stuff with `position`

desugaring to

main =
    when binarySearch [1, 3, 4] 4 is
        NotFound -> Err "number not found in list"
        Found position ->
            # do many lines of stuff with `position`

view this post on Zulip Brendan Hansknecht (Aug 02 2023 at 23:26):

I think that will be too confusing.

view this post on Zulip timotree (Aug 02 2023 at 23:33):

I kind of agree about the specific syntax. Maybe with some more natural keywords the feature could be useful though

view this post on Zulip timotree (Aug 02 2023 at 23:35):

Roc doesn't have a concept of early returns right? In Rust you could write

let position = match binary_search([1, 3, 4], 4) {
    NotFound => return Err("number not found in list"),
    Found(position) => position,
};

but in Roc I'm not sure if there's a general way to avoid the indentation

view this post on Zulip timotree (Aug 02 2023 at 23:36):

I guess many concrete use cases like Result will have an andThen method which is compatible with normal backpassing

view this post on Zulip Brendan Hansknecht (Aug 03 2023 at 00:58):

Your analysis is correct

view this post on Zulip Brian Carroll (Aug 03 2023 at 06:59):

Early return is really an imperative concept, but there is a functional equivalent. You use functions like Result.try or Task.await to build up a pipeline of operations, and exit on the first failure. The back-passing feature in Roc was created to make this pattern ergonomic.

view this post on Zulip Brian Carroll (Aug 03 2023 at 07:00):

Oh yeah you mentioned that!


Last updated: Jun 16 2026 at 16:19 UTC