Created
August 17, 2016 18:06
-
-
Save gaku-sei/ce836f14c6522c7282186905581f25d2 to your computer and use it in GitHub Desktop.
Sum and Product in Rust
This file contains 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::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