solutions/cw5/fact.fun
author Christian Urban <christian.urban@kcl.ac.uk>
Fri, 29 Nov 2024 18:59:32 +0000
changeset 976 e9eac62928f5
parent 894 02ef5c3abc51
permissions -rw-r--r--
updated
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
864
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     1
// a simple factorial program
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     2
// (including a tail recursive version)
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     3
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     4
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     5
def fact(n: Int) : Int =
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     6
  if n == 0 then 1 else n * fact(n - 1);
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     7
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     8
def facT(n: Int, acc: Int) : Int =
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     9
  if n == 0 then acc else facT(n - 1, n * acc);
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    10
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    11
def facTi(n: Int) : Int = facT(n, 1);
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    12
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    13
def top() : Void = {
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    14
  print_int(fact(6));
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    15
  print_char(',');
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    16
  print_int(facTi(6));
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    17
  print_char('\n')
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    18
};
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    19
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    20
top()
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    21