Skip to content

Instantly share code, notes, and snippets.

@danellis
Created December 11, 2018 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danellis/03a27f729ace9f3d5216809693844d6d to your computer and use it in GitHub Desktop.
Save danellis/03a27f729ace9f3d5216809693844d6d to your computer and use it in GitHub Desktop.
Rust workshop part 1
use std::env;
struct Stats {
max: f64,
mean: f64,
min: f64,
size: u64,
sum: f64,
}
fn main() {
let numbers: Vec<f64> = env::args()
.skip(1)
.map(|n| n.parse::<f64>().unwrap())
.collect();
if numbers.is_empty() {
eprintln!("Usage: cargo run <num>...");
return;
}
let first = numbers[0];
let initial = Stats {
max: first,
mean: first,
min: first,
size: 1,
sum: first
};
if numbers.len() < 2 {
println!("{}", format_result(initial));
return;
}
let result = numbers[1..].fold(initial, |a: Stats, b: f64| Stats {
max: a.max.max(b),
mean: (a.sum + b) / (a.size as f64 + 1.0),
min: a.min.min(b),
size: a.size + 1,
sum: a.sum + b
});
println!("{}", format_result(result));
}
fn format_result(result: Stats) -> String {
return format!(
"max: {}, mean: {}, min: {}, size: {}, sum: {}",
result.max, result.mean, result.min, result.size, result.sum
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment