Skip to content

Instantly share code, notes, and snippets.

@gicappa
Created April 20, 2018 23:07
Show Gist options
  • Save gicappa/b8ac432d2962d256ae3c3634fc64b274 to your computer and use it in GitHub Desktop.
Save gicappa/b8ac432d2962d256ae3c3634fc64b274 to your computer and use it in GitHub Desktop.
Total price in three sauces...
fn total_price(&self, shopping_list: &[&str]) -> Option<f32> {
let mut total = 0.0;
for item in shopping_list {
if self.price(item) == None {
return None;
}
total += self.price(item).unwrap();
}
Some(total)
}
fn total_price(&self, shopping_list: &[&str]) -> Option<f32> {
shopping_list.iter().fold(Some(0.0), |acc, &item| {
match self.price(item) {
Some(x) => Some(x + acc.unwrap()),
None => None,
}
});
}
fn total_price(&self, shopping_list: &[&str]) -> Option<f32> {
shopping_list.iter().fold(Some(0.0), |acc, &item| {
acc.and_then(|a| self.price(item).map(|p| p + a) )
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment