The Fibonacci Number: a new L+ example
I’ve just added a new example to illustrate the capabilities of the L+ language: fibo.lp
If you read our last post then, as you might recall, last Saturday we released a Free (as in Freedom) compiler called the “L+ compiler”. This program was a mandatory assignment we had to develop for a Compiler course at the Catholic University of Uruguay back in 2006.
When we introduced the compiler, we featured a simple “Hello World” program that illustrated a basic example of L+, our language. The example was very basic though, so I wanted to raise the bar and show what our little language can do.
This new program reads a number from stdin, calculates its corresponding Fibonacci number and prints the results to stdout.
The good thing about this example is that it illustrates most of L+ in action, including: I/O, function declarations, recursion, branching and string processing.
Here’s the full source code for the example. You can find it at the L+ project homepage and you also get it when you checkout the source code from Subversion.
// Calculate the Fibonacci number for n int fibo(int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } return fibo(n-1) + fibo(n-2); } // Program fibo.lp // Read a number, calculate the Fibonacci number for said number // and print a message with the result. void main() { print("Enter number to calculate the Fibonacci number for:"); string nStr = read(); int f = fibo(toInt(nStr)); string s = toString(f); print("The Fibonacci number for " + nStr + " is: " + s); }
From a compiler developer’s point of view, I can hardly tell you what it felt like seeing our compiler handling a source code as complex as this one and even catching some grammar errors every time I forgot to add a semicolon to a line.
I really encourage you to test this program, but in case you don’t, here’s the output the L+ compiler produces while compiling this program (yeah, it’s really verbose):
[ale@syaoran fibo]$ LPC_HOME=/opt/lpc /opt/lpc/bin/compiler.sh fibo.lp Cleaning up directory for new build... Checking for necessay files... compiler... assembler... L+ standard library... Java... Looking for L+ source file Starting the build process... Invoking the L+ compiler... Batch mode. taking as input: fibo.lp Parsing successful Pretty Printing result. Saving as "out.txt" Begin semantic validation... Optimizing... Pretty Printing optimized code. Saving as "opt.txt" Compiling into file "comp.j" Optimizing object code. Saving as "compopt.j" Freeing used memory... Invoking the Jasmin JVM assembler... Generated: Main.class Build process completed successfully! type 'java Main' to run the compiled program.
Finally, this is the output produced from running the program with an input value of “10”:
[ale@syaoran fibo]$ java Main Enter number to calculate the Fibonacci number for: 10 The Fibonacci number for 10 is: 55.0