Skip to content

New syntax proposal: Conditional matching #6037

Closed
@brendanzab

Description

@brendanzab

Currently if you want to match only on conditionals you have to use a pointless expression at the beginning of the match and use _ at the beginning of each line.

match x {
    _ if x >= 0 => x / y,
    _ if y >  0 => ((x + 1) / y) - 1,
    _           => ((x + 1) / y) + 1,
}

I have also noticed this used out on a blog post (under the heading First version…).

Yes, you could always use if/else, but it's ugly in some use cases.

if x >= 0 { x / y }
else if y > 0 { ((x + 1) / y) - 1 }
else { ((x + 1) / y) + 1 }

// with formatting
if x >= 0 {
    x / y
} else if y >  0 {
    ((x + 1) / y) - 1
} else {
    ((x + 1) / y) + 1
}

// or maybe:
if      x >= 0 { x / y }
else if y >  0 { ((x + 1) / y) - 1 }
else           { ((x + 1) / y) + 1 }

What if when you leave out the expression at the beginning of the match you could only match on conditionals? This would be equivalent to Scheme's cond.

match {
    if x >= 0 => x / y,
    if y >  0 => ((x + 1) / y) - 1,
    _         => ((x + 1) / y) + 1,
}

Maybe you could even get rid of the ifs and just take boolean expressions, although I think it sacrifices some readability.

match {
    x >= 0 => x / y,
    y >  0 => ((x + 1) / y) - 1,
    _      => ((x + 1) / y) + 1,
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions