How to do memoization or memoisation in Julia 1.0

前端 未结 3 1631
遇见更好的自我
遇见更好的自我 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:36

    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 BigInts 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
    

提交回复
热议问题