Understanding the constraint with generic functions

One drawback of the preceding method is that we must define the original function as an anonymous function rather than a generic function. That seems to be a major constraint. The question is why doesn't it work with generic function?

Let's do a quick test by starting a new Julia REPL, defining the original fib function again, and wrapping it with the same memoize function:

The problem is that fib is already defined as a generic function, and it cannot be bound to a new anonymous function, which is what is being returned from the memoize function. To work around the issue, we may be tempted to assign the memoized function with a new name:

fib_fast = memoize(fib)

However, it does not really work because the original fib function makes a recursive call to itself rather than the new memoized version. To see it more clearly, we can unroll a call as follows:

  1. Call the function as fib_fast(6).
  2. In the fib_fast function, it checks whether the cache contains a key that equals 6. 
  3. The answer is no, so it calls fib(5).
  4. In the fib function, since n is 5 and is greater than 3, it calls fib(4) and fib(3) recursively.

As you can see, the original fib function got called rather than the memoized version, so we are back to the same problem before. Hence, if the function being memoized uses recursion, then we must write the function as an anonymous function. Otherwise, it would be okay to create a memoized function with a new name. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.165.246