2 Three ways to implement the f acto rial function in SPL.
3 First the recursive version .
5 facR(n) :: Int -> Int {
13 //The iterative version of the factorial function
14 facl ( n ) :: Int -> Int {
23 //A main function to check the results
24 //It takes no arguments, so the type looks like this:
31 if (facN != factl (n) || facn != facL (n)){
32 print (n : facN : facl (n) : facL (n): []);
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
45 //Generates a list of integers from the first to the last argument
46 fromTo (from, to) :: Int Int -> [Int] {
48 return from:fromTo(from+1, to);
54 //Make a reversed copy of any list
55 reverse(list):: [t] -> [t] {
57 while(!isEmpty(list)){
64 //Absolute value, in a strange layout
65 abs(n)::Int->Int{if(n<0)return -n; else return n;}
67 //swap the elements in a tuple
68 swap(tuple) :: (a, a) -> (a, a){
70 tuple.fst = tuple.snd;
76 append(l1, l2) :: [t] [t] -> [t] {
80 l1.tl = append(l1.tl, l2);
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){
91 list.hd = list.hd*list.hd;
92 list.tl = squareOddNumbers(list.tl);
96 //deze comment eindigt met EOF ipv newline