Browse Source

add some type stuff

jmelesky 7 năm trước cách đây
mục cha
commit
b1c6bce594
1 tập tin đã thay đổi với 60 bổ sung1 xóa
  1. 60 1
      tutorial1/src/main.rs

+ 60 - 1
tutorial1/src/main.rs

@@ -1,14 +1,68 @@
 // 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)]
+// same with variables
+#![allow(unused_variables)]
 
 extern crate rand;
 
 use rand::Rng;
 
 
+// record types
+struct Point {
+    x: i32,
+    y: i32
+}
+
+fn nullrecordtypetest() {
+    let v = Point {x:1, y:2};
+    let s = v.x + v.y;
+}
+
+
+// free type parameters
+
+// according to the compiler, type parameters should be camelcase,
+// not lowercase. tutorial page included 'a', 'b', and 't'. we'll change
+// those to 'typeA', 'typeB', 'typeT'.
+//
+// wait, apparently it means upper camel case.
+// 'TypeA', 'TypeB', 'TypeT'
+
+type Pair<TypeA,TypeB> = (TypeA,TypeB);
+
+// id<t> : |t| -> t
+fn id<TypeT>(x: TypeT) -> TypeT { x }
+
+
+// algebraic datatypes
+
+// Option exists in the prelude, so MyOption
+// ... and MyNone, MySome
+enum MyOption<TypeT> {
+    MyNone,
+    MySome(TypeT)
+}
+
+// (x:MyOption<_>) does not work here, nor
+// does (x:MyOption<TypeName>)
+// using i32 to get it to compile
+fn nullalgebraicdatatypes(x:MyOption<i32>) -> bool {
+    // have to import the constructor names?
+    use MyOption::MyNone;
+    use MyOption::MySome;
+    match x {
+        MyNone     => false,
+        MySome(_)  => true
+    }
+}
+
+
+
+// function types and definitions
+
 // f : |int,int| -> int
 fn f (x:i32, y:i32) -> i32 { x + y }
 
@@ -38,6 +92,8 @@ fn fact (n:u64) -> u64 {
 }
 
 
+// effect-ful recursion
+
 fn collatz(n:i32) {
     let v = match n % 2 {
         0 => n / 2,
@@ -48,6 +104,9 @@ fn collatz(n:i32) {
     if v != 1 { collatz(v) }
 }
 
+
+// playground
+
 fn main() {
     let start = rand::thread_rng().gen_range(1,101);