From: John Carter Date: 2006-01-27T05:59:02+09:00 Subject: Re: Memoization? On Fri, 27 Jan 2006, Dave Howell wrote: > > On Jan 22, 2006, at 19:14, John Carter wrote: > >> Trick Two... >> >> Memoization >> >> class Foo >> def initialize( thing) >> end >> end >> >> foo = Foo.new( thing) >> >> becomes... >> >> class Foo >> @@memo = Hash.new{|hash,key| hash[key] = Foo.new( key)} >> >> def create_foo( thing) >> @@memo[thing] >> end >> >> def initialize( thing) >> end >> >> end >> >> >> foo = Foo.create_foo( thing) > > Er, um, huh? > > All foo-links are tapping into a global-to-class hash called @@memo. OK... > Foo.new has been rendered useless, apparently torturing anybody who forgets > by returning nil as a non-error? > Foo.create_foo(thing) does, well, I have no idea. What's "thing" supposed to > be? And why is create_foo using square brackets? > > Sigh. Sometimes Ruby is *too* idiomatic. > > What *is* "memo-ization?" I sense deep confuzzlement so let's take that a lot slower. OK, so this trick cannot be used everywhere. For example if I ask you to give me a new pink car, I expect you to go off, build a new car, paint it pink and give it to me. If are ask you again, I expect you to do it again and give me another (different) brand new pink car. Suppose in the particular application I had I didn't really care it was a different one, I just wanted a pink car NOW, fast. If it's the same one as you gave me last time, in this particular application, I don't care so long as it isn't blue. I could have kept hold of the old pink car, but that's too much work, sometimes I use green, sometimes red cars, sometimes pink. This is a garbage collected system, so it's easier for me grab a new pink car when I need one than to keep track of my old ones. This form of memo-ization is just to skip the "new" when I already have made one pink car, and just give exactly the same one as I made last time. Ok, now the little idiomatic bit. Suppose @@memo is a brand spanking new empty Hash object. What does @@memo["pink"] return? By default it returns nil. But you can make it return whatever you damn well feel like. @@memo = Hash.new{|hash,key| hash[key] = Car.new(key)} @@memo["pink"] Will say, oo, I have no "pink" element, I better go off and make one then, fortunately I have a block on my "new" so I know how to do that. ps. If everybody in your country had a pink car, what would you have? Answer: A Pink Carnation. Ok, so using pink cars was a "blooming" silly example... :-)) John Carter Phone : (64)(3) 358 6639 Tait Electronics Fax : (64)(3) 359 4632 PO Box 1645 Christchurch Email : john.carter@tait.co.nz New Zealand Carter's Clarification of Murphy's Law. "Things only ever go right so that they may go more spectacularly wrong later." From this principle, all of life and physics may be deduced.