I have been trying to do memorisation in Julia for the Fibonacci function. This is what I came up with.
The original unmodified code (for control purposes)
Since the arguments to the function are integers, you can use a simple array, which will be faster than a Dict
(make sure you use BigInt
s in the cache for large arguments to avoid overflow):
function fib(n, cache=sizehint!(BigInt[0,1],n))
n < length(cache) && return cache[n+1]
f = fib(n-1,cache) + fib(n-2,cache)
push!(cache,f)
return f
end