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