Skip to content

Instantly share code, notes, and snippets.

@NickyMeuleman
Created June 21, 2021 14:09
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 NickyMeuleman/d90e3012724fdededff22cea0f621e6b to your computer and use it in GitHub Desktop.
Save NickyMeuleman/d90e3012724fdededff22cea0f621e6b to your computer and use it in GitHub Desktop.
Exercism.io Rust, proverb
// 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