forked from HeapVisCapstone/benchmarks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNatArith.java
More file actions
81 lines (68 loc) · 1.69 KB
/
NatArith.java
File metadata and controls
81 lines (68 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public class NatArith {
public static void main(String[] args) {
Nat m = Nat.fromInt(1921);
System.out.println(m);
Nat n = Nat.fromInt(3385);
System.out.println(n);
System.out.println("1921 + 3385 = " + m.plus(n));
}
}
abstract class Nat {
public static Nat fromInt(int i) {
if (i == 0) {
return new Zero();
} else {
return new Succ(i-1);
}
}
public Nat succ() { return new Succ(this); }
public abstract Nat plus(Nat n);
public abstract Nat minus(Nat n);
public abstract int toInt();
@Override
public String toString() {
return Integer.toString(this.toInt());
}
}
class Zero extends Nat {
public Zero() { return; }
public Nat plus(Nat n) { return n; }
public Nat minus(Nat n) { return this; }
public int toInt() { return 0; }
}
class Succ extends Nat {
final private Nat prev;
public Succ(Nat n) {
prev = n;
}
public Succ(int i) {
assert i >= 0;
if (i == 0) {
prev = new Zero();
} else {
prev = new Succ(i-1);
}
}
public Nat getPrev() {
return prev;
}
public Nat plus(Nat n) {
if (n instanceof Zero) {
return this;
} else {
Succ ns = (Succ) n;
return this.succ().plus(ns.getPrev());
}
}
public Nat minus(Nat n) {
if (n instanceof Zero) {
return n;
} else {
Succ ns = (Succ) n;
return this.getPrev().minus(ns.getPrev());
}
}
public int toInt() {
return 1 + this.getPrev().toInt();
}
}