You never assign any memorized value to the cache. As @xlembouras said, you didn't memorize anything.
class FactorialClass
@@sequence = [1]
def self.of( n )
# @@sequence[n] get evaluated to nil unless n is 0, always!
@@sequence[n] || n * of( n - 1 )
end
end
You need to manually assign memorized value to the cache, after you finish the computation.
class FactorialClass
@@sequence = [1]
def self.of( n )
@@sequence[n] = (@@sequence[n] || n * of( n - 1 ))
end
end
However, does memorization really works for your factorial computation? No.
f(n) = n * f(n-1) = n * ((n-1) * f(n-2)) = ... = n * ((n-1) * (... * (3 * f(2))))
All the recursion step calculates the factorial of a new value (from 2 to n), which hasn't been calculated before. The memorization won't get hit at any step.