Skip to content

Instantly share code, notes, and snippets.

@derekmorr
Created October 4, 2016 17:53
Show Gist options
  • Save derekmorr/4f3a5790db998606674316e28f71f518 to your computer and use it in GitHub Desktop.
Save derekmorr/4f3a5790db998606674316e28f71f518 to your computer and use it in GitHub Desktop.
fold examples for Tom
use std::cmp;
fn sum(numbers: Vec<i32>) -> i32 {
numbers.iter().fold(0, |total, num| total + num)
}
fn biggest_word(words: Vec<&str>) -> usize {
words.iter().fold(0, |length, word| cmp::max(length, word.chars().count()))
}
fn main() {
let numbers = vec![1,2,3,4,5,6,7,8,9,10];
let total = sum(numbers);
println!("the total of 1 to 10 is {}", total);
let words = vec!["foo", "bar", "blah", "stuff", "thing", "the"];
let biggest = biggest_word(words);
println!("the longest word has length {}", biggest);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment