I'm trying to get a better understanding of ZFC set theory, in particular how a computer program might model the axiom of infinity to "construct" natural numbers. The typical symbols I've seen used to construct the natural numbers are: "{", "}", and ",".
The code below works, but I'm hoping for a purely recursive solution. One that given a natural number (here using int), recursively builds up the corresponding string into its set-theoretic encoding and then returns it. Ideally, I hope for it to work without using any extra data structures like the String array currently being used.
It's ok if the runtime is slow (exponential). Using recursion sometimes makes the expression of the process simpler, more condensed/elegant and easier to understand, and I would very much like to see what such a solution for this might look like, regardless of performance. Ultimately, I'd like a better understanding of foundations of math/numbers. I have many questions but thought this might be a good way to begin. Thanks!
// Converts an natural number to its ZFC set notation:
// 0 = {}, 1 = {0} = {{}}, 2 = {0,1} = {{},{{}}},
// 3 = {0,1,2} = {{},{{}},{{},{{}}}} ...
import java.util.Scanner;
public class IntToSetNotation {
private static final String openBrace = "{";
private static final String closeBrace = "}";
private static final String seperator = ",";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.println(getSetNotationFromInt(n));
}
private static String getSetNotationFromInt(int n) {
String[] nums = new String[n+1];
nums[0] = openBrace + closeBrace;
for (int i = 1; i < nums.length; i++) {
if(i == nums.length-1)
nums[i] = openBrace + getPrevSets(i,nums) + closeBrace;
else
nums[i] = seperator + openBrace + getPrevSets(i,nums) + closeBrace;
}
return nums[n];
}
private static String getPrevSets(int n, String[] nums) {
String s = "";
for (int i = 0; i<n; i++)
s += nums[i];
return s;
}
}
The second helper method isn't necessary. Here is a shortened version.
public class IntToSetNotationRecursive {
private static final String openBrace = "{";
private static final String closeBrace = "}";
private static final String separator = ",";
public static void main(String[] args) {
for (int i = 0; i < 6; i++) {
System.out.println(i + " = " + getSetNotationFromInt(i));
}
}
static String getSetNotationFromInt(int n){
return helper1(n, n, "");
}
static String helper1(int n, int x, String s){
if(x<=0)
return openBrace + s + closeBrace;
return helper1(n, x-1, helper1(x-1,x-1,"") + ((x != n ) ? separator : "") + s);
}
}
Prints:
0 = {}
1 = {{}}
2 = {{},{{}}}
3 = {{},{{}},{{},{{}}}}
4 = {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}
5 = {{},{{}},{{},{{}}},{{},{{}},{{},{{}}}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}}