856
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 |
|