How to do memoization or memoisation in Julia 1.0

前端 未结 3 1618
遇见更好的自我
遇见更好的自我 2021-02-04 15:58

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)



        
3条回答
  •  死守一世寂寞
    2021-02-04 16:20

    The simplest way to do it is to use get!

    const fibmem = Dict{Int,Int}()
    function fib(n)
        get!(fibmem, n) do
            n < 3 ? 1 : fib(n-1) + fib(n-2)
        end
    end
    

    Note the const specifier outside fibmem. This avoids the need for global, and will make the code faster as it allows the compiler to use type inference within fib.

提交回复
热议问题