Skip to content

Instantly share code, notes, and snippets.

@gaku-sei
Created August 17, 2016 18:06
Show Gist options
  • Save gaku-sei/ce836f14c6522c7282186905581f25d2 to your computer and use it in GitHub Desktop.
Save gaku-sei/ce836f14c6522c7282186905581f25d2 to your computer and use it in GitHub Desktop.
Sum and Product in Rust
use std::convert::From;
use std::ops::{Add, Mul};
trait Sumable<T> {
fn sum(&self) -> T;
}
trait Productable<T> {
fn product(&self) -> T;
}
impl<T> Sumable<T> for Vec<T> where T: Add<Output = T> + From<i32> + Copy {
fn sum(&self) -> T {
self.iter().fold(T::from(0), |acc, &x| acc + x)
}
}
impl<T> Productable<T> for Vec<T> where T: Mul<Output = T> + From<i32> + Copy {
fn product(&self) -> T {
self.iter().fold(T::from(1), |acc, &x| acc * x)
}
}
fn main() {
println!("{}", vec![2, 3, 5].sum());
println!("{}", vec![2, 3, 5].product());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment