added some type checking stuff. vardecl now works for basictypes and unary operators
[cc1516.git] / examples / example.spl
1 /*
2 Three ways to implement the f acto rial function in SPL.
3 First the recursive version .
4 */
5 Int r = 1;
6 Char r = 1;
7 Int r = -1;
8 Void r = 0;
9 Bool r = !True;
10 Bool r = -True;
11 //var facN = 1;
12 //var ok = True;
13
14 facR(n) :: Int -> Int {
15 if (n < 2) {
16 return 1;
17 } else {
18 return n * facR(n-1);
19 }
20 }
21
22
23 //The iterative version of the factorial function
24 facl ( n ) :: Int -> Int {
25 var r = 1;
26 while(n>1){
27 r = r*n;
28 n = n-1;
29 }
30 return r;
31 }
32
33 //A main function to check the results
34 //It takes no arguments, so the type looks like this:
35 main ( ) :: Void {
36 var n = 0;
37 var facN = 1;
38 var ok = True;
39 while(n<20) {
40 facN = facR (n);
41 if (facN != factl (n) || facn != facL (n)){
42 print (n : facN : facl (n) : facL (n): []);
43 ok=False;
44 }
45 }
46 print(ok);
47 }
48
49 // A list based factorial function
50 // Defined here to show that functions can be given in any order (unlike C)
51 facL (n) :: Int -> Int {
52 return product (fromTo(1, n) ); //Inline comments yay
53 }
54
55 //Generates a list of integers from the first to the last argument
56 fromTo (from, to) :: Int -> Int -> [Int] {
57 if(from <= to){
58 return from:fromTo(from+1, to);
59 } else {
60 return [];
61 }
62 }
63
64 //Make a reversed copy of any list
65 reverse(list):: [t] -> [t] {
66 var accu = [];
67 while(!isEmpty(list)){
68 accu = list.hd:accu;
69 list = list.tl;
70 }
71 return accu;
72 }
73
74 //Absolute value, in a strange layout
75 abs(n)::Int->Int{if(n<0)return -n; else return n;}
76
77 //swap the elements in a tuple
78 swap(tuple) :: (a, a) -> (a, a){
79 var tmp = tuple.fst;
80 tuple.fst = tuple.snd;
81 tuple.snd = tmp;
82 return tuple;
83 }
84
85 //list append
86 append(l1, l2) :: [t] -> [t] -> [t] {
87 if(isEmpty(l1)){
88 return l2;
89 } else {
90 l1.tl = append(l1.tl, l2);
91 return l1;
92 }
93 }
94
95 //square the odd numbers in a list and remove the even members
96 squareOddNumbers(list) :: [Int] -> [Int] {
97 while(!isEmpty (list) && list.hd % 2==0){
98 list=list.tl;
99 }
100 if(!isEmpty(list)){
101 list.hd = list.hd*list.hd;
102 list.tl = squareOddNumbers(list.tl);
103 }
104 return list;
105 }
106 //deze comment eindigt met EOF ipv newline