Created
October 4, 2016 17:53
-
-
Save derekmorr/4f3a5790db998606674316e28f71f518 to your computer and use it in GitHub Desktop.
fold examples for Tom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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