Created
March 13, 2023 16:26
-
-
Save Leowbattle/d459a69136432b60622b28bec401b4c0 to your computer and use it in GitHub Desktop.
Implementing natural numbers with Peano arithmetic in Java π
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainProgram { | |
public static void main(String[] args) { | |
Nat n1 = Nat.int2Nat(10); | |
Nat n2 = Nat.int2Nat(20); | |
Nat n3 = n1.add(n2); | |
int x = Nat.nat2Int(n3); | |
System.out.println(x); | |
} | |
} | |
abstract class Nat { | |
public abstract Nat add(Nat n); | |
public static Nat int2Nat(int n) { | |
if (n == 0) { | |
return new Zero(); | |
} else { | |
return new Succ(int2Nat(n - 1)); | |
} | |
} | |
public static int nat2Int(Nat n) { | |
if (n instanceof Succ s) { | |
return 1 + nat2Int(s.x); | |
} else { | |
return 0; | |
} | |
} | |
} | |
class Zero extends Nat { | |
@Override | |
public Nat add(Nat n) { | |
return n; | |
} | |
} | |
class Succ extends Nat { | |
public Nat x; | |
public Succ(Nat x) { | |
this.x = x; | |
} | |
@Override | |
public Nat add(Nat n) { | |
return new Succ(x.add(n)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is equivalent to the following Haskell code: