Anonymous functions

Sunday, November 29, 2009
Anonymous functions are now working, as shown in the following example:

def testAnonFn {
  let f = fn (i:int) -> int {
    return i + i;
  Debug.assertEq(2, f(1));
  Debug.assertEq(4, f(2));

The keyword 'fn' basically means 'lambda'. In this case, the lambda function is being assigned to the variable 'f', which is then called in the two assert statements below.

Note however, that the lambda is not yet a true closure, although I have started work on that. For now, the anonymous function can't access local variables from the outer scope. (Although it can indeed access variables from global scopes, since otherwise the '+' operation would not compile.)

I have thought about allowing the 'fn' keyword to be dropped entirely if there are no arguments and no return values - essentially the equivalent of a clang block - which would be designated with just { and }. I'm not sure that this is a great idea, though. There are other possible uses of {} (map literals, perhaps, although those could easily be done via [ => ] as well.) From a parsing standpoint, there's no ambiguity problems - it's easy to distinguish a "block" from a "suite", except in the case of a standalone suite that is not part of some other statement, in which case semantically they are the same thing anyway.

The advantage would be that you could do things like "onExit({ print("Bye!"); })" as opposed to "onExit(fn { print("Bye!"); })". Not sure if the small increase in brevity is really worth it.

-- Talin


Post a Comment