Created
March 20, 2014 14:05
-
-
Save wunki/9664468 to your computer and use it in GitHub Desktop.
Total in FP and OOP
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
/*** | |
* | |
* If we list all the natural numbers below 10 that are multiples of 3 or 5, we | |
* get 3, 5, 6 and 9. The sum of these multiples is 23. | |
* | |
* Find the sum of all the multiples of 3 or 5 below 1000. | |
* | |
***/ | |
fn is_multiple(num: int) -> bool { | |
num % 3 == 0 || num % 5 == 0 | |
} | |
fn total_oop(max: int) -> int { | |
//! Returns the total in an OOP manner | |
let mut total = 0; | |
for n in range(0, max) { | |
if is_multiple(n) { | |
total += n | |
} | |
}; | |
total | |
} | |
fn total_functional(max: int) -> int { | |
//! Returns the total in without mutable state | |
range(0, max).filter(|&n| is_multiple(n)).fold(0, |a, b| a + b) | |
} | |
fn main() -> () { | |
println!("Total is {:d}", total_oop(1000)) | |
} | |
#[test] | |
fn test_seven_is_not_multiple() { | |
if is_multiple(7) { | |
fail!("7 is not a multiple of 3 or 5"); | |
} | |
} | |
#[test] | |
fn test_five_is_multiple() { | |
if !is_multiple(5) { | |
fail!("Five is multiple of 5!") | |
} | |
} | |
#[test] | |
fn test_nine_is_multiple() { | |
if !is_multiple(9) { | |
fail!("Five is multiple of 9!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment