I've this code, which is having 4 casting as
in single line, which I feel is annoying, is there a way to avoid/reduce them?
fn main() {
let series = [
30,21,29,31,40,48,53,47,37,39,31,29,17,9,20,24,27,35,41,38,
27,31,27,26,21,13,21,18,33,35,40,36,22,24,21,20,17,14,17,19,
26,29,40,31,20,24,18,26,17,9,17,21,28,32,46,33,23,28,22,27,
18,8,17,21,31,34,44,38,31,30,26,32];
series[..slen].iter().zip(&series[slen..])
.map(|(&a, &b)| (b as f32 - a as f32) / slen as f32).sum::<f32>() / slen as f32
}
UPDATE
As thread is closed, and I can't post a reply, I'm posting the way I found as an update here, I think the best way is to use macro
as below:
macro_rules! sub{
($first:expr, $($others:expr), *) => {
{
let mut sub = $first as f64;
$(sub -= $others as f64;)*
sub
}
};
}
macro_rules! div{
($first:expr, $second:expr) => {
$first as f64 / $second as f64
};
}
// Then call them as:
div!(series[..slen].iter().zip(&series[slen..])
.map(|(&a, &b)| div!(sub!(b, a), slen)).sum::<f64>(),
slen)
I think it has even better readability than this:
series[..slen].iter().zip(&series[slen..])
.map(|(&a, &b)| (b as f64 - a as f64) / slen as f64).sum::<f64>() / slen as f64
But not sure about performance