From: "Jesús Gabriel y Galán" Date: 2008-10-29T02:56:43+09:00 Subject: Re: memoization example the ruby programming language question On Tue, Oct 28, 2008 at 5:32 PM, Hiro Protagonist wrote: > 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? This: class Proc; include Functional; end adds the method "memoize" to the Proc class. This: lambda {|x| return 1 if x==0; x*factorial[x-1]; } creates a Proc object, which, by means of the above extension has a method memoize. With this: lambda {|x| return 1 if x==0; x*factorial[x-1]; }.memoize you call the method memoize of the created Proc object. Maybe this is more clear: temp_proc = lambda {|x| return 1 if x==0; x*factorial[x-1]; } factorial = temp_proc.memoize() The method memoize returns a Proc itself. This new Proc maintains a cache of calls. When there's a cache miss, it calls the original Proc (check uses of "self" inside the memoize method). When there's a cache hit, the original proc is not called, and the cached value is returned instead. > 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). Yes, but factorial here is not your original proc. It's the proc returned but the memoize method. > 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 think you are confusing the terms here. "memoize" is a method of proc objects that returns a proc. Let me know if this sheds some light... Jesus.