Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
def factorial
factorial = { int n, BigInteger accu = 1G ->
    if (n < 2) return accu
     factorial.trampoline(n - 1, n * accu)
}
factorial = factorial.trampoline()

assert factorial(1)    == 1
assert factorial(3)    == 1 * 2 * 3
assert factorial(1000) == 402387260... // plus another 2560 digits

...

The Groovy compiler reads the source code, builds and an Abstract Syntax Tree (AST) from it, and then puts the AST into bytecode. With AST transformations, the programmer can hook into this process. A general description of this process, an exhaustive description of all available transformations, and a guide of how to write you own ones can be found for example in Groovy in Action, 2nd Edition (MEAP), chapter 9.

...