To demonstrate the memoization, we can use an executable Kotlin script like this:
#!/usr/bin/env kotlin -Xjvm-default=all -cp build/jam-0.9.jar
interface FibonacciExample : Project {
fun fib(x : Long) : Long = if (x < 2) x else fib(x - 1) + fib(x - 2)
fun demo() {
println("fib(10) = ${fib(10)}")
}
}
Project.run(FibonacciExample::class.java, FibonacciExample::demo, args)
and then run it: % ./fibonacci.kts
[compute] demo
[compute] fib 10
[compute] fib 9
[compute] fib 8
[compute] fib 7
[compute] fib 6
[compute] fib 5
[compute] fib 4
[compute] fib 3
[compute] fib 2
[compute] fib 1
[compute] fib 0
[current] fib 1
[current] fib 2
[current] fib 3
[current] fib 4
[current] fib 5
[current] fib 6
[current] fib 7
[current] fib 8
fib(10) = 55
The Jam runtime logging displays the fib(x) calls as they recurse down to the fib(1) and fib(0) base cases, and also shows how duplicate calls are eliminated by returning memoized results from the cache.When the script completes the cache is saved to a local file. If we run the same script again, the result is ready to go:
% ./fibonacci.kts
[compute] demo
[current] fib 10
fib(10) = 55