cwtests/cw05/fact.fun
author Christian Urban <christian.urban@kcl.ac.uk>
Sun, 10 Sep 2023 12:24:55 +0100
changeset 917 89e05a230d2d
parent 856 23273e3a120f
permissions -rw-r--r--
updated
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
856
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     1
// a simple factorial program
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     2
// (including a tail recursive version)
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     3
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     4
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     5
def fact(n: Int) : Int =
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     6
  if n == 0 then 1 else n * fact(n - 1);
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     7
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     8
def facT(n: Int, acc: Int) : Int =
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     9
  if n == 0 then acc else facT(n - 1, n * acc);
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    10
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    11
def facTi(n: Int) : Int = facT(n, 1);
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    12
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    13
def top() : Void = {
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    14
  print_int(fact(6));
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    15
  print_char(',');
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    16
  print_int(facTi(6));
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    17
  print_char('\n')
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    18
};
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    19
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    20
top()
23273e3a120f updated
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    21