[Newbies] Re: Beginners Digest, Vol 18, Issue 2
Oscar Nierstrasz
oscar.nierstrasz at gmail.com
Thu Oct 4 12:02:38 UTC 2007
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
More information about the Beginners
mailing list