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