Created
June 21, 2021 14:09
-
-
Save NickyMeuleman/d90e3012724fdededff22cea0f621e6b to your computer and use it in GitHub Desktop.
Exercism.io Rust, proverb
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
// adding one item to an iterator by calling .chain() with an argument that implements IntoIterator | |
pub fn build_proverb(list: &[&str]) -> String { | |
match list.is_empty() { | |
true => String::new(), | |
false => list | |
.windows(2) | |
.map(|window| format!("For want of a {} the {} was lost.", window[0], window[1])) | |
.chain( | |
// first() returns an Option which implements IntoIterator and can be .chain()ed to an other iterator | |
list.first() | |
.map(|item| format!("And all for the want of a {}.", item)), | |
) | |
.collect::<Vec<_>>() | |
.join("\n"), | |
} | |
} | |
// adding one item to an iterator by calling .chain() with an iterator that contains a single item by using std::iter::once | |
pub fn build_proverb1(list: &[&str]) -> String { | |
match list.is_empty() { | |
true => String::new(), | |
false => list | |
.windows(2) | |
.map(|window| format!("For want of a {} the {} was lost.", window[0], window[1])) | |
.chain(std::iter::once(format!( | |
"And all for the want of a {}.", | |
list[0] | |
))) | |
.collect::<Vec<_>>() | |
.join("\n"), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment