Stream: beginners

Topic: ✔ Destructuring on `if` conditions?


view this post on Zulip Ian Liu Rodrigues (Dec 06 2023 at 17:35):

Is it possible to de-structure tagged values on if conditions, like in pattern matching? Something like:

if foo == Ok x then
    dbg x
else if foo == Err y then
    dbg y

view this post on Zulip Sven van Caem (Dec 06 2023 at 17:47):

If I understand correctly, no. To do pattern matching, you'd have to use a when ... is expression

view this post on Zulip Ian Liu Rodrigues (Dec 06 2023 at 17:58):

I was thinking about the following use case of nested when blocks, which could be flattened if the if expression could also destructure:

when cond1 is
    Foo (Ok a) -> ...
    Foo (Err _) -> ...
    x -> when (x, cond2) is
        (Bar, Baz) -> ...
        _ -> ...

Flattened if's

if cond1 == Foo (Ok a) then
    ...
else if cond1 == Foo (Err _) then
    ...
else if (cond1, cond2) == (Bar, Baz) then
    ...
else
    ...

view this post on Zulip Notification Bot (Dec 06 2023 at 18:10):

Ian Liu Rodrigues has marked this topic as resolved.

view this post on Zulip Sven van Caem (Dec 06 2023 at 18:19):

if flattening is what you're looking for, maybe pattern matching on (cond1, cond2) fits your use case?

view this post on Zulip Brian Carroll (Dec 06 2023 at 21:46):

Yeah exactly, like this:

when (cond1, cond2) is
   (Foo (Ok a), _) -> ...
   (Foo (Err _), _) -> ...
   (Bar, Baz) -> ...

Last updated: Jul 06 2025 at 12:14 UTC