Boiethios
Boiethios

Reputation: 42739

How to add a condition to a match in case ... of

In functional languages, one can add a condition to a branch of a pattern matching: for example, in OCaml:

let value = match something with
| OneThing -> "1"
| Another when condition -> "2"
| _ -> "3"

How to do this in elm? I tried when and if, but nothing worked.

Upvotes: 2

Views: 1456

Answers (2)

bdukes
bdukes

Reputation: 155895

As an alternative to using an if within the case branch, you might want to instead match against a tuple containing the condition, which would look like this:

let
    value =
        case ( something, condition ) of
            ( OneThing, _ ) ->
                "1"

            ( Another, True ) ->
                "2"

            _ ->
                "3"

Upvotes: 3

Chad Gilbert
Chad Gilbert

Reputation: 36375

Elm does not have conditionals within pattern matching, probably because the language designers tend to prefer to keep syntax small and simple.

The best you can do is something like this:

let
    value =
        case something of
            OneThing ->
                "1"

            Another ->
                if condition then
                    "2"
                else
                    ...

            _ ->
                "3"

Upvotes: 5

Related Questions