summaryrefslogtreecommitdiff
path: root/tests/arr2/arr2.toc
blob: 7056416ca57941b2f5f43bdbad187a2cd74a30ff (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
puti ::= fn(x: int) {
	 #C("extern int printf(const char *fmt, ...)");
	 #C("printf(\"%ld\\n\", (long)x);
");
};
putf ::= fn(x: float) {
	 #C("extern int printf(const char *fmt, ...)");
	 #C("printf(\"%f\\n\", (double)x);
");
};

// it would be nice if Arr.data.len == Arr.len (: but this will require some C code...
Arr ::= fn (t :: Type) Type {
	struct {
		   data : []t;
		   len, cap : int;
	}
};

arr_add ::= fn(t ::=, a : &Arr(t), x : t) {
		if a.len >= a.cap {
		   a.cap = a.cap * 2 + 2;
		   new_data := new(t, a.cap);
		   each i := 0..a.len-1 {
		   		new_data[i] = a.data[i];
		   }
		   a.data = new_data;
		}
		a.data[a.len] = x;
		a.len += 1;
};

square ::= fn(t ::=, x : t) t {
	   a : Arr(t);
	   each i := 1,2..2*x-1 {
	   		arr_add(&a, i);
	   };
	   sum := 0 as t;
	   each i := 0..a.len-1 {
	   		sum += a.data[i];
	   };
	   sum
};


// ArrInt ::= Arr(int);

inc ::= fn(t ::=, x : t) t {
	x + 1
};

main ::= fn() {
	 arr : Arr(int);
	 farr : Arr(float);
	 each i := 1..100 {	
	 	   arr_add(&arr, inc(square(i)));
	 	   arr_add(&farr, inc(square(i as float)));
	 }
	 each i := 0..arr.len - 1 {
	 	  puti(arr.data[i]);
	 }
	 each i := 0..farr.len - 1 {
	 	  putf(farr.data[i]);
	 }
};