logo       

Re: Re: Beginners Digest, Vol 18, Issue 2: msg#00019

lang.smalltalk.squeak.beginners

Subject: Re: Re: Beginners Digest, Vol 18, Issue 2


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


<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise