|
@@ -1,5 +1,7 @@
|
|
|
// some cut-and-paste and transcription from http://science.raphael.poss.name/rust-for-functional-programmers.html
|
|
|
|
|
|
+// defining a bunch of functions, but only trying a few at a time.
|
|
|
+
|
|
|
#![allow(dead_code)]
|
|
|
|
|
|
extern crate rand;
|
|
@@ -11,12 +13,30 @@ use rand::Rng;
|
|
|
fn f (x:i32, y:i32) -> i32 { x + y }
|
|
|
|
|
|
// fact : |int| -> int
|
|
|
-fn fact (n:i64) -> i64 {
|
|
|
+// this will overflow the int
|
|
|
+fn fact_rec (n:u64) -> u64 {
|
|
|
if n == 1 { 1 }
|
|
|
else { n * fact(n-1) }
|
|
|
}
|
|
|
|
|
|
|
|
|
+// fact : |int| -> int
|
|
|
+// the fold also overflows, but faster
|
|
|
+fn fact (n:u64) -> u64 {
|
|
|
+ (1..n+1).fold(1, |p,n| p*n)
|
|
|
+
|
|
|
+ // (1..n+1) -- right-exclusive range interval
|
|
|
+ // inclusive range is available as "experimental", and looks like: (1...n+1)
|
|
|
+ // you can '#![feature(inclusive_range_syntax)]'
|
|
|
+ // but 'feature' doesn't work on the stable releases, you need a nightly
|
|
|
+
|
|
|
+ // fold - defined in the std::iter::Iterator, which is exposed
|
|
|
+ // by the rust prelude: https://doc.rust-lang.org/std/prelude/
|
|
|
+
|
|
|
+ // fold takes 2 arguments: initial value, and closure
|
|
|
+ // |foo| expr -- this is a closure. can also be |foo| { block }
|
|
|
+}
|
|
|
+
|
|
|
|
|
|
fn collatz(n:i32) {
|
|
|
let v = match n % 2 {
|
|
@@ -34,6 +54,17 @@ fn main() {
|
|
|
println!("{}", start);
|
|
|
collatz(start);
|
|
|
|
|
|
- println!("fact: {}", fact(i64::from(start)));
|
|
|
+ // println!("fact: {}", fact(i64::from(start)));
|
|
|
+ // there is no i -> u 'from'
|
|
|
+ // println!("fact: {}", fact(start as u64));
|
|
|
+
|
|
|
+ for i in 1..10 {
|
|
|
+ println!("{}, {}", i, fact_rec(i))
|
|
|
+ }
|
|
|
+
|
|
|
+ for i in 1..10 {
|
|
|
+ println!("{}, {}", i, fact(i))
|
|
|
+ }
|
|
|
+
|
|
|
}
|
|
|
|