Java Magazine, Mar/Apr 2018
ORACLE COM JAVAMAGAZINE MARCH APRIL 2018 65 jvm languages else fibonacci n 1 fibonacci n 2 The key is the @ Memoized annotation which triggers a corresponding AST transformation Any evaluation of the fibonacci method defined this way will involve many repeated calculations even for small arguments For example fibonacci 5 fibonacci 4 fibonacci 3 fibonacci 3 fibonacci 2 fibonacci 2 fibonacci 1 and so on To prevent the combinatorial explosion in the number of repeated calculations the @ Memoized AST transform generates a cache of values in which the keys are the arguments and the values are the results of evaluating the operation That means each computation of fibonacci n is stored in a map of n to the result With the AST transformation applied its fast and easy to compute higher values such as assert fibonacci 100 1298777728820984005 Another AST transformation provided in the Groovy standard library is @ TailRecursive If you can write an algorithm in such a way that the last evaluated expression is a recursive call with different arguments the transform will convert the recursive calls into iterative ones For example see the following factorial calculation import groovy transform @ TailRecursive def fact n acc BigInteger ONE n 2 acc fact n BigInteger ONE n acc def result fact 70000 println result size 308760 digits
You must have JavaScript enabled to view digital editions.