I put the finishing touches in on my Java interpreter for my small functional language experiment.
main! => (printLine! "Hello world!")
The language is based on expression lists where each successive expression is applied to the previous expression if possible. The hello world example first evaluates printLine! and then applies a string constant to it, causing it to print. => is the declaration operator and is used to bind the result of an expression to a name.
Lambdas are curried by design (simplifies a lot, both for partial application of functions and for me as the interpreter implementer). Here we declare that add is a lambda with one argument returning a lambda taking another argument and summing the arguments.
sum => x -> y -> (x + y)
The language is optionally typed and currently has no type enforcement, but typed syntax is allowed (just not implemented yet). That would look like this:
sumInts => x: Int -> y: Int -> (x + y)
x is evaluated, + is applied to x (+ is a method of Int) which returns a partially applied function which is then evaluated when y is applied to it. x $ + $ y, you could say.
KiloGram => type (amount: Int)
Declares a type with one field, amount, of type Int. Ints, Longs and other primitives are objects too. This makes the language quite slow but if performance becomes important I'll write a compiler instead. Or something. Performance isn't a priority currently.
FiveKilos => (new KiloGram 5)
We instantiate the KiloGram type as you would expect. Same syntax as Java.
member double => self -> (self amount * 2)
There's a method returning double the amount of the KiloGram. The member keyword by default attaches the method to the type that was last declared; but the language has open classes and we can add another method at any time and any place to any type.
member triple of KiloGram => self -> (self amount * 3)
And since some of you may be wondering where the assignments are, they're done using the <- (store in) operator.
Stores the value 0 in variable index. Type inference sets index to an Int.
There are more features that I haven't included in this post because I'm not sure anyone else is interested in seeing more and I feel I've scratched the itch of showing off the language for criticism now.
Some of the features not shown, but implemented, are:
- Module syntax
- Require for loading other files
- C FFI (built on JNA for simplicity)
- Conditionals as expressions
Technical details: the parser is generated by ANTLR according to a 60-line grammar, JUnit is used to test various cases (that's been invaluable so far), and JNA is used to access C libraries (for the FFI; because at this stage I prefer ease of use to speed).
If anyone is interested in hearing more or trying out the interpreter or seeing the source just ask and I'll gladly share
EDIT: I forgot, functional languages always show off their factorial functions, well, here's mine
factorial => x -> if (x = 0) then 1 else (x * (factorial (x - 1)))