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