Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use '<' and '>' in match?

I am trying to do a simple quadratic function that would return number of roots and their values via an enum:

enum QuadraticResult {
    None,
    OneRoot(f32),
    TwoRoots(f32, f32),
}

fn solveQuadratic(a: f32, b: f32, c: f32) -> QuadraticResult {
    let delta = b * b - 4.0 * a * c;
    match delta {
        < 0 => return QuadraticResult::None,
        > 0 => return QuadraticResult::TwoRoots(0.0, 1.0),
        _ => return QuadraticResult::OneRoot(0.0),
    }
}

This doesn't compile as it complains about '<' and '>'. Is there a way to achieve this with match or do I need to use if

like image 484
dawid Avatar asked Dec 17 '17 04:12

dawid


People also ask

What is multiline matching?

Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.

How do you match with newline?

"\n" matches a newline character.

Which pattern is used to match any non What character?

The expression \w will match any word character. Word characters include alphanumeric characters ( - , - and - ) and underscores (_). \W matches any non-word character.


3 Answers

You can use a match guard, but that feels more verbose than a plain if statement:

return match delta {
    d if d < 0 => QuadraticResult::None,
    d if d > 0 => QuadraticResult::TwoRoots(0.0, 1.0),
    _   => QuadraticResult::OneRoot(0.0),
}
like image 192
Jacob Krall Avatar answered Oct 23 '22 09:10

Jacob Krall


If you want to handle the three cases where some value is greater than, equal to or less than another, you can match on an Ordering, which you can obtain by calling cmp (from the Ord trait) or partial_cmp (from the PartialOrd trait).

fn solve_quadratic(a: f32, b: f32, c: f32) -> QuadraticResult {
    let delta = b * b - 4.0 * a * c;
    match delta.partial_cmp(&0.0).expect("I don't like NaNs") {
        Ordering::Less => QuadraticResult::None,
        Ordering::Greater => QuadraticResult::TwoRoots(0.0, 1.0),
        Ordering::Equal => QuadraticResult::OneRoot(0.0),
    }
}
like image 25
Francis Gagné Avatar answered Oct 23 '22 10:10

Francis Gagné


You can, but you'll want to create a variable binding when you do it and turn it into an actual expression:

match delta {
    d if d < 0.0 => QuadraticResult::None,
    d if d > 0.0 => QuadraticResult::TwoRoots(0.0, 1.0),
    _ => QuadraticResult::OneRoot(0.0),
}

I'm not sure this is any better than just splitting this into an if statement though.

like image 11
Simon Whitehead Avatar answered Oct 23 '22 09:10

Simon Whitehead