#Calculate a bunch of numbers in the fibonacci sequence.
#See how, since the function is memoized,
#results are generated very quickly, even though the
#recursive implementation is well-known for its slowness.
for n in {0:25} do
print "fib({n}) = {\fibonacci(n)}"
end
#Remove `cache` to see how slow this function can be.
cache function fibonacci
if {@1 < 2} then return {@1} end
return {\fibonacci(@1-1) + \fibonacci(@1-2)}
end
#As an extra bit of homework, try comparing the speed of various compilation methods, after removing the `cache` keyword.
# 1. Interpreted: `time paisley examples/fibonacci.pai`
# This is the default way to run scripts.
# 2. Compiled to a Lua VM running Paisley bytecode: `paisley examples/fibonacci.pai --standalone --target=c --output=test_pgm && time ./test_pgm`
# This has no speed improvement over the previous option.
# The only benefit here is that the program is completely standalone,
# and does not require either Lua or Paisley to be installed on the host machine.
# 3. Compiled to a C++ VM running the bytecode: `paisley examples/fibonacci.pai --standalone --target=cpp --output=test_pgm && time ./test_pgm`
# This is the fastest, by a large margin.
# The initial compilation step is by far the slowest (the initial compile of the runtime may take a minute or two, but is only compiled once),
# but the resulting program runs blazingly fast by comparison.