Last active
June 25, 2019 15:14
-
-
Save dustinknopoff/5b4a5d3eb2bea758d11c1931193f16c7 to your computer and use it in GitHub Desktop.
some fibonacci sequence fns using fold
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
fn main() { | |
fn fibo_fancy(val: i32) -> i32 { | |
if val == 0 { | |
return 0 | |
} | |
(1..=val) | |
.fold((None, None), |acc, curr| { | |
let (m1, m2) = acc; | |
if curr <= 2 { | |
match (m1, m2) { | |
(None, Some(m)) => (Some(m), Some(1)), | |
(Some(m), None) => (Some(m), Some(1)), | |
(None, None) => (None, Some(1),), | |
_ => unreachable!(), | |
} | |
} else { | |
match (m1, m2) { | |
(Some(m1), Some(m2)) => { | |
let tmp = m1 + m2; | |
(Some(m2), Some(tmp)) | |
} | |
_ => unreachable!(), | |
} | |
} | |
}) | |
.1 | |
.unwrap() | |
} | |
assert_eq!(fibo_fancy(0), 0); | |
assert_eq!(fibo_fancy(1), 1); | |
assert_eq!(fibo_fancy(2), 1); | |
assert_eq!(fibo_fancy(3), 2); | |
assert_eq!(fibo_fancy(4), 3); | |
assert_eq!(fibo_fancy(5), 5); | |
assert_eq!(fibo_fancy(29), 514229); | |
} |
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
fn main() { | |
fn fibo_fancy(val: i32) -> i32 { | |
if val == 0 { | |
return 0 | |
} | |
(1..=val) | |
.fold((0, 0), |acc, curr| { | |
let (m1, m2) = acc; | |
if curr <= 2 { | |
match (m1, m2) { | |
(0, 0) => (0, 1), | |
(0, num) => (num, 1), | |
(num, 0) => (num, 1), | |
_ => unreachable!(), | |
} | |
} else { | |
let tmp = m1 + m2; | |
(m2, tmp) | |
} | |
}) | |
.1 | |
} | |
assert_eq!(fibo_fancy(0), 0); | |
assert_eq!(fibo_fancy(1), 1); | |
assert_eq!(fibo_fancy(2), 1); | |
assert_eq!(fibo_fancy(3), 2); | |
assert_eq!(fibo_fancy(4), 3); | |
assert_eq!(fibo_fancy(5), 5); | |
assert_eq!(fibo_fancy(29), 514229); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment