Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / Compilers, Introduction / coolc-spim / my-code / list.cl
blob: 374e600a7f882179c74c9eb9c9028e8b899ccfe9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
(* Although this is written from scratch, it is hard to end up with something
   much different from what is presented in the original Stanford cs143 course.
   So credit for this code goes to Alex Aiken, creator of that course. *)
class List {
  item: Object;
  next: List;

  init(i: Object, n: List): List {
    {
      item <- i;
      next <- n;
      self;
    }
  };

  flatten(): String {
    let string: String <-
      case item of
        i: Int => (new A2I).i2a(i);
        s: String => s;
        o: Object => { abort(); ""; };
      esac
    in
      if isvoid next
        then string
        else string.concat(next.flatten())
      fi
  };
};

class Main inherits IO {
  main(): Object {
    let hello: String <- "Hello ",
        world: String <- "World! ",
        answer: Int <- 42,
        newline: String <- "\n",
        -- if abort is added to the list, program will abort
        abort: Object <- new Object,
        nil: List,
        list: List <- (new List).init(hello,
                        (new List).init(world,
                          (new List).init(answer,
                            (new List).init(newline,
                            --  (new List).init(abort,
                            nil)
                            --)
                          )
                        )
                      )
    in
      out_string(list.flatten())
  };
};