Simplify this code?

Is there anyway this simplify this 5 line block?

                let delta = if *n > 1 {
                    (upper - lower) / ((n - 1) as f32)
                } else {

here n is a &usize, thus our need for *n – but that is not what I want to simplify. What I want to say her eis:

if n is 1, then the delta is 0.0; otherwise, it’s (upper-lower)/(n-1).

This is where C style ternary test? true_expr : false_expr really comes in handy, or being able to drop the {}'s

In Rust, is there anyway to simplify this down to 1 line (besides writing a custom macro).


Not really any way to simplify it… But you can already put it on one line:

let delta = if *n > 1 {(upper - lower) / ((n - 1) as f32)} else {0.0_f32};

And the C-like version wouldn’t be much shorter:

let delta = (*n > 1)? (upper - lower) / ((n - 1) as f32) : 0.0_f32;

You can always put it into a function:

let delta = compute_delta(n, upper, lower);

Name this and put in a separate function. It seems to me it does have a meaning (average/share?). A name will make it more clear, and you can even put a longer comment explaining what it is and what it does.

let delta = (upper - lower) / (usize::max(n - 1, 1) as f32);

This is assuming you don’t add delta to anything when n == 1 except when it is multiplied by 0.

If you need to use it more than once, I’m with everyone else: just give it a function! :stuck_out_tongue:

It’s the interval between n equally spaced points, with the first at lower and the last at upper.

Moreover, the purpose of the if is to make it well-defined for the case of a single point. Can’t speak for why, but I do know this is a common need when working with polylines (e.g. n=1 would be the case where a point is created for each vertex of a polyline; n=10 is when a point is created for each vertex as well as 9 points in-between each pair; etc.)

This is clever+ You’re right, when n==1, I don’t use delta.