I'm trying to implement L-system as functions. For example, dragon curve looks like this:
static String F(int n) {
return n == 0 ? "F" : F(n - 1) + "+" + G(n -1);
}
static String G(int n) {
return n == 0 ? "G" : F(n - 1) + "-" + G(n -1);
}
@Test
void testDragonCurveAsStaticFunction() {
assertEquals("F", F(0));
assertEquals("F+G", F(1));
assertEquals("F+G+F-G", F(2));
assertEquals("F+G+F-G+F+G-F-G", F(3));
}
I want to implement this with lambda functions. I got the following implementation by referring to recursion - Implement recursive lambda function using Java 8 - Stack Overflow.
@Test
void testDragonCurveAsLambdaFunction() {
interface IntStr { String apply(int i); }
IntStr[] f = new IntStr[2];
f[0] = n -> n == 0 ? "F" : f[0].apply(n - 1) + "+" + f[1].apply(n - 1);
f[1] = n -> n == 0 ? "G" : f[0].apply(n - 1) + "-" + f[1].apply(n - 1);
assertEquals("F", f[0].apply(0));
assertEquals("F+G", f[0].apply(1));
assertEquals("F+G+F-G", f[0].apply(2));
assertEquals("F+G+F-G+F+G-F-G", f[0].apply(3));
}
Is there a way to implement this without using an array?
But I want to create a generic L-System, so I don't want to define a new class, interface or method for the dragon curve.