progs/fun2/fact.fun
author Christian Urban <christian.urban@kcl.ac.uk>
Fri, 28 Oct 2022 09:08:13 +0100
changeset 893 54a483a33763
parent 854 ce4a7bab6bd8
permissions -rw-r--r--
updated
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
854
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     1
// a simple factorial program
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     2
// (including a tail recursive version)
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     3
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     4
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     5
def fact(n: Int) : Int =
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     6
  if n == 0 then 1 else n * fact(n - 1);
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     7
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     8
def facT(n: Int, acc: Int) : Int =
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
     9
  if n == 0 then acc else facT(n - 1, n * acc);
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    10
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    11
def facTi(n: Int) : Int = facT(n, 1);
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    12
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    13
def top() : Void = {
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    14
  print_int(fact(6));
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    15
  print_char(',');
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    16
  print_int(facTi(6));
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    17
  print_char('\n')
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    18
};
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    19
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    20
top()
ce4a7bab6bd8 testcases
Christian Urban <christian.urban@kcl.ac.uk>
parents:
diff changeset
    21