Hi all,
Attached is the example of memoization from the above book.
I am awed by ruby.
I understand what the program does in that I inserted puts statements
to follow it’s logic. It definitely caches the recursive calls. In
fact you can even enlarge the cache by asking for a larger factorial and
the factorial Lambda Proc object will not do any unnecessary
computations and use cached results if they exist. For example if I
initially do factorial.call(4) the results will be cached. If I then do
factorial.call(5) it will do a computation and use the factorial.call(4)
cached result saving considerable amount of work.
I marked the line that I don’t understand. I want an explanation in
terms of syntax. If cache has data why is method memoize called first?
I understand the initially recursive calls when cache is empty. In empty
cache scenario the factorial lambda Proc keeps being called recursively
until x == 0. Once this happens memoize is called up the stack for each
factorial call and data is cached for each value of x. But when cache
is full and momoization is used. Why does it go to method memoize
first? I just don’t see it syntactically. This example may use some
ruby 1.9 syntax. I think factorial[x-1] is equivalent to
factorial.call(x-1).
I need an explanation of syntax. Also I have never seen the syntax:
factorial = lambda {|x| return 1 if x==0; x*factorial[x-1]; }.memoize
where the memoize method is attached to end of lambda {}. Does
factorial PROC object contain lambda block plus the appended memoize
method?
I understand what it does but I am missing the syntax.
Thanks,
pete