Stream: ideas

Topic: List pattern matching rest variable


view this post on Zulip Luke Boswell (Mar 24 2023 at 06:18):

I added an issue 5187 to track a feature request for a ..restvariable in list pattern matching. This should be an efficient operation now that we have seamless slices.

For example, currently in Roc an eatWhitespace function could look like the following;

eatWhitespace = \bytes ->
    when bytes is
        [' ', ..] -> eatWhitespace (List.dropFirst bytes)
        ['\n', ..] -> eatWhitespace (List.dropFirst bytes)
        ['\r', ..] -> eatWhitespace (List.dropFirst bytes)
        ['\t', ..] -> eatWhitespace (List.dropFirst bytes)
        _ -> bytes

However if we support a rest variable this could be written as follows;

eatWhitespace = \bytes ->
    when bytes is
        [' ', ..rest] -> eatWhitespace rest
        ['\n', ..rest] -> eatWhitespace rest
        ['\r', ..rest] -> eatWhitespace rest
        ['\t', ..rest] -> eatWhitespace rest
        _ -> bytes

view this post on Zulip Luke Boswell (Mar 24 2023 at 06:21):

And another motivating example which shows variable length matches,

decodeBool = Decode.custom \bytes, @Json {} ->
    when bytes is
        ['f', 'a', 'l', 's', 'e', ..rest] -> { result: Ok Bool.false, rest }
        ['t', 'r', 'u', 'e', ..rest] -> { result: Ok Bool.true, rest }
        _ -> { result: Err TooShort, rest: bytes }

view this post on Zulip Folkert de Vries (Mar 24 2023 at 07:15):

You can use the as keyword there

view this post on Zulip Nick Hallstrom (Mar 24 2023 at 07:18):

How does the as keyword work?

view this post on Zulip Nick Hallstrom (Mar 24 2023 at 07:21):

Woah like this?

foo =
    when [1, 2, 3, 4] is
        [1, .. as b] -> b
        _ -> []

I had no idea you could do that, neat! That's not in the tutorial right now is it?

view this post on Zulip Luke Boswell (Mar 24 2023 at 12:01):

Does that feature work at the moment? I tried to make an example using as but it crashed.

view this post on Zulip Folkert de Vries (Mar 24 2023 at 12:10):

it should work, yes

view this post on Zulip Nick Hallstrom (Mar 24 2023 at 16:41):

I am also getting a crash. roc check works but then roc build is failing
Screenshot-2023-03-24-at-10.38.01-AM.png
Here's the commit with the issue


Last updated: Jun 16 2026 at 16:19 UTC