compound/lib.rs
1//! *********** Typical usage ***************
2//!
3//! use compound;
4//!
5//! fn main() {
6//! let percentages = [10., 11., 23., 34.];
7//! let initial_investment: f64 = 1000.00;
8//! let balance = compound( &initial_investment, &percentages);
9
10//! println!("Your balance is {}", balance );
11//! println!("The percentages were {:?}", percentages);
12//! }
13
14//! > major change: just noticed that primitives already implement the copy trait
15//! and therefore wouldn't mutate anything
16pub fn compound(investment: f64, returns: &[f64]) -> f64 {
17 (returns.iter().fold(investment, |value, perc | {
18 value * ( 1. + (perc / 100. ))
19 }) * 100.).round() / 100.
20}
21
22// compound should work with vectors
23// #[cfg(test)]
24#[test]
25fn test_compound_vectors() {
26 let percentages = vec![10.2, -11.3, 23.5, -34., 0.];
27 let init_value = 1000.00;
28
29 let balance = compound(init_value, &percentages);
30
31 assert_eq!(balance, 796.74);
32
33 // the passed in vector should still be available
34 assert_eq!(percentages, vec![10.2, -11.3, 23.5, -34., 0.]);
35}
36
37// compound should work with slices
38// #[cfg(test)]
39#[test]
40fn test_compound_slices() {
41 let percentages = [10.2, -11.3, 23.5, -34., 0.];
42
43 let balance = compound(1000.00, &percentages);
44
45 assert_eq!(balance, 796.74);
46}
47
48// *** Special Thanks to zsck, marciaux, exoticon for helping out ***
49// See discussion at: https://users.rust-lang.org/t/pull-me-out-of-insanity-cant-wrap-my-head-around-this-error-expected-std-vec-vec-f64-found---4-expected-ptr-found-array-of-4-elements-e0308/6688
50