Skip to content

Instantly share code, notes, and snippets.

@tafsiri
Created December 26, 2010 06:05
Show Gist options
  • Save tafsiri/755245 to your computer and use it in GitHub Desktop.
Save tafsiri/755245 to your computer and use it in GitHub Desktop.
#fib with memoization
fakeClosure := Object clone
fakeClosure memo := Map clone
fakeClosure fibmemo := method(num,
#I need this next line when i assign this method to a slot in the
#outer object (see last line of this gist).
#Feels like a 'this/self' binding issue. Otherwise i would have expected
#the memo slot on fakeClosure to be visible here
memo := fakeClosure memo #not strictly necessary when calling 'fakeClosure fibmemo'
memo atPut(0 asString, 0)
memo atPut(1 asString, 1)
fibhelp := method(num,
one := memo at((num-1) asString)
two := memo at((num-2) asString)
if(one == nil
, one = fibhelp(num-1,memo)
memo atPut((num-1) asString, one)
)
if(two == nil
, two = fibhelp(num-2,memo)
memo atPut((num-2) asString, two)
)
one + two
)
fibhelp(num,memo)
)
#not really necessary, but i wanted it to be uniform with the other calls
#makes line 9 necessary
fibmemo := fakeClosure getSlot("fibmemo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment