Browse Source

some code monkeying from functional rust page

jmelesky 7 years ago
parent
commit
3b1979af2c
2 changed files with 47 additions and 0 deletions
  1. 8 0
      tutorial1/Cargo.toml
  2. 39 0
      tutorial1/src/main.rs

+ 8 - 0
tutorial1/Cargo.toml

@@ -0,0 +1,8 @@
+[package]
+name = "func_tutorial_1"
+version = "0.1.0"
+authors = ["jmelesky"]
+
+[dependencies]
+
+rand = "0.3.14"

+ 39 - 0
tutorial1/src/main.rs

@@ -0,0 +1,39 @@
+// some cut-and-paste and transcription from http://science.raphael.poss.name/rust-for-functional-programmers.html
+
+#![allow(dead_code)]
+
+extern crate rand;
+
+use rand::Rng;
+
+
+// f : |int,int| -> int
+fn f (x:i32, y:i32) -> i32 { x + y }
+
+// fact : |int| -> int
+fn fact (n:i64) -> i64 {
+   if n == 1 { 1 }
+   else { n * fact(n-1) }
+}
+
+
+
+fn collatz(n:i32) {
+    let v = match n % 2 {
+        0 => n / 2,
+        _ => 3 * n + 1
+    };
+
+    println!("{}", v);
+    if v != 1 { collatz(v) }
+}
+
+fn main() {
+    let start = rand::thread_rng().gen_range(1,101);
+
+    println!("{}", start);
+    collatz(start);
+
+    println!("fact: {}", fact(i64::from(start)));
+}
+