Skip to content

Instantly share code, notes, and snippets.

@Leowbattle
Created March 13, 2023 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leowbattle/d459a69136432b60622b28bec401b4c0 to your computer and use it in GitHub Desktop.
Save Leowbattle/d459a69136432b60622b28bec401b4c0 to your computer and use it in GitHub Desktop.
Implementing natural numbers with Peano arithmetic in Java 😎
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));
}
}
@Leowbattle
Copy link
Author

This is equivalent to the following Haskell code:

data Nat = Zero | Succ Nat

add :: Nat -> Nat -> Nat
add Zero     y = y
add (Succ x) y = Succ (add x y)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment