Why Does This Memoization Implementation Work On Anonymous Functions But Not Work On Declared Functions?
Solution 1:
Yes, it's right that only the first call is memoized in the second and third scenarios.
In the first scenario the reference to the original function only exists as a value, then memoize
is applied to that and the fibonacci
variable contains the reference to the memoized function.
In the second and third scenario fibonacci
is a reference to the original function. The value of the expression fibonaci.memoize()
that contains the reference to the memoized function only exist as a value before it is called once.
The memoize
method doesn't change the original function, instead it returns a new function that wraps the original function. The original function is unchanged, and to use the memoization you have to call the function returned by the memoize
method.
In the first scenario when the function makes a recursive call to fibonacci
, it's the memoized function that is used. In the second and third scenarios when the recursive call is made, fibonacci
is the original function instead.
Post a Comment for "Why Does This Memoization Implementation Work On Anonymous Functions But Not Work On Declared Functions?"