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
snake_case
for identifiers.solve_quadratic
notsolveQuadratic
. – Hydria0.0
and1.0
with calculated values. Be careful not to assume that, whenQuadraticResult::TwoRoots(x, y)
is returned,x != y
. Even ifd
is greater than 0,-b + d.sqrt()
and-b - d.sqrt()
may still be the same. Here's an easy example, but it could happen with finite roots too. You may want to returnOption<(x1, x2)>
and let the caller decide whetherx1
andx2
are "close enough" to be considered a single root. – Anubis