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)
function fib(x)
if x < 3
return 1
else
return fib(x-2) + fib(x-1)
end
end
This is my first attempt
memory=Dict()
function memfib(x)
global memory
if haskey(memory,x)
return memory[x]
else
if x < 3
return memory[x] = 1
else
return memory[x] = memfib(x-2) + memfib(x-1)
end
end
end
My second attempt
memory=Dict()
function membetafib(x)
global memory
return haskey(memory,x) ? memory[x] : x < 3 ? memory[x]=1 : memory[x] = membetafib(x-2) + membetafib(x-1)
end
My third attempt
memory=Dict()
function memgammafib!(memory,x)
return haskey(memory,x) ? memory[x] : x < 3 ? memory[x]=1 : memory[x] = memgammafib!(memory,x-2) + memgammafib!(memory,x-1)
end
Are there other ways of doing so that I am not aware of?
Memoize.jl
package?get!(memory, x) do; x < 3 ? 1 memfib(x-1) + memfib(x-2) end
. But other than that: this question is better suited for Code Review, since you are asking about improvements for working code.