Stream: beginners

Topic: ✔ Pattern matching on a number range.


view this post on Zulip Ian McLerran (Jan 02 2024 at 01:13):

Does Roc support pattern matching on a number range? If so what is the syntax? For example I would like to do something like the following:

httpResponseType =\code ->
    when code is
        200 -> Ok
        201 -> Created
        202 -> Accepted
        203 to 299 -> Success
        300 to 399 -> Redirect
        400 -> BadRequest
        401 -> Unauthorized
        403 -> Forbidden
        404 -> NotFound
        405 to 499 -> ClientError
        500 to 599 -> InternalError

The to keyword is of course incorrect syntax, but is there a way to do this correctly?

view this post on Zulip Luke Boswell (Jan 02 2024 at 01:32):

You can do something like this

interface Example
    exposes []
    imports []

matchOnRange = \in ->
    when in is
        20 -> Twenty
        a if a >= 203 && a <= 299 -> Success
        _ -> SomethingElse

expect matchOnRange 20 == Twenty
expect matchOnRange 204 == Success

view this post on Zulip Ian McLerran (Jan 02 2024 at 03:40):

Thanks!

view this post on Zulip Notification Bot (Jan 02 2024 at 03:40):

Ian McLerran has marked this topic as resolved.


Last updated: Jul 06 2025 at 12:14 UTC