<div dir="ltr"><div>Certainly it's not common to want to memoize a method, but I was wondering if it would be easy to do. I came up with the following that works well. I'd be interested in hearing whether there is a better approach and whether something like this is already in the base image and I just haven't found it yet.</div><div><br></div><div>I added the <font face="monospace">Object</font> instance method <font face="monospace">memoize:</font> which takes a block.<br>This caches previously computed values in an <font face="monospace">IdentityDictionary</font><br>that is saved in <font face="monospace">Smalltalk</font>Â which is also an <font face="monospace">IdentityDictionary</font>.<br><br><font face="monospace">memoize: aBlock<br>Â Â | cache cacheKey sender valueKey |<br><br>Â Â sender := thisContext sender.<br><br>Â Â "Smalltalk is a SystemDictionary which is an IdentityDictionary.<br>Â Â That is why cacheKey must be a Symbol."<br>Â Â cacheKey := ('cache-', sender name) asSymbol.<br><br>Â Â cache := Smalltalk at: cacheKey ifAbsentPut: [ IdentityDictionary new ].<br>Â Â valueKey := thisContext name, sender arguments asString :: asSymbol.<br><br>Â Â ^ cache at: valueKey ifAbsentPut: [ aBlock value ].</font><br><br>Using the <font face="monospace">memoize:</font> method is demonstrated in the class method <font face="monospace">average:</font> below<br>(added to any class) which takes an array of numbers.<br><br></div><div><font face="monospace">average: numberArray<br>Â Â ^ self memoize: [<br>Â Â Â Â | sum |<br>Â Â Â Â 'computing average' print.<br>Â Â Â Â sum := numberArray fold: [:acc :n | acc + n].<br>Â Â Â Â sum / numberArray size.<br>Â Â ].</font><br></div><div><br></div><span class="gmail_signature_prefix">-- </span><br><div dir="ltr" class="gmail_signature" data-smartmail="gmail_signature"><div dir="ltr"><div><div dir="ltr"><div><div dir="ltr"><div dir="ltr"><div><font face="arial, helvetica, sans-serif">R. Mark Volkmann</font></div><div><span style="font-size:12.8000001907349px"><font face="arial, helvetica, sans-serif">Object Computing, Inc.</font></span></div></div></div></div></div></div></div></div></div>