Here's another solution that, like Bert's, does not require an instance variable or an additional class. the advantage, I think, is that the concerns of computing the result and managing the cache are separated, so it is easy to adapt to other situations:

Integer>>fib
        self assert: self >= 1.
        ^ self fibWithCache: Dictionary new.! !

Integer>>fibLookup: cache
        ^ cache at: self ifAbsentPut: [ self fibWithCache: cache ] ! !

Integer>>fibWithCache: cache
        self assert: self >= 1.
        (self == 1) ifTrue: [ ^1].
        (self == 2) ifTrue: [ ^1].
        ^ ((self - 1) fibLookup: cache) + ((self - 2) fibLookup: cache)! !

Here too, the caching version is only slightly modified from the slow, non-caching version.

Integer>>fibSlow
        self assert: self >= 1.
        (self == 1) ifTrue: [ ^1].
        (self == 2) ifTrue: [ ^1].
        ^ (self - 1) fib + (self - 2) fib! !

Oscar

_______________________________________________
Beginners mailing list
Beginners@lists.squeakfoundation.org
http://lists.squeakfoundation.org/mailman/listinfo/beginners

Reply via email to