[Cuis-dev] memoizing a method

Mark Volkmann r.mark.volkmann at gmail.com
Thu Dec 5 13:24:24 PST 2024


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.

I added the Object instance method memoize: which takes a block.
This caches previously computed values in an IdentityDictionary
that is saved in Smalltalk which is also an IdentityDictionary.

memoize: aBlock
    | cache cacheKey sender valueKey |

    sender := thisContext sender.

    "Smalltalk is a SystemDictionary which is an IdentityDictionary.
    That is why cacheKey must be a Symbol."
    cacheKey := ('cache-', sender name) asSymbol.

    cache := Smalltalk at: cacheKey ifAbsentPut: [ IdentityDictionary new ].
    valueKey := thisContext name, sender arguments asString :: asSymbol.

    ^ cache at: valueKey ifAbsentPut: [ aBlock value ].

Using the memoize: method is demonstrated in the class method average: below
(added to any class) which takes an array of numbers.

average: numberArray
    ^ self memoize: [
        | sum |
        'computing average' print.
        sum := numberArray fold: [:acc :n | acc + n].
        sum / numberArray size.
    ].

-- 
R. Mark Volkmann
Object Computing, Inc.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.cuis.st/mailman/archives/cuis-dev/attachments/20241205/003fb41c/attachment.htm>


More information about the Cuis-dev mailing list