Skip to content

Instantly share code, notes, and snippets.

@seiffert
Created December 23, 2012 20:17
Show Gist options
  • Save seiffert/4365771 to your computer and use it in GitHub Desktop.
Save seiffert/4365771 to your computer and use it in GitHub Desktop.
FibonacciSequence := Object clone
FibonacciSequence cache := List clone
FibonacciSequence simple := method (num,
if (num <= 2,
1,
self calc(num)
)
)
FibonacciSequence calc := method (num,
if (self cached (num),
self cached (num),
doCache(num, self simple (num-1) + self simple (num-2))
)
)
FibonacciSequence cached := method (num,
self cache at(num)
)
FibonacciSequence doCache := method (num, result,
if (self cache at(num),
self cache atPut(num, result),
self cache append(result)
);
result
)
for (i, 1, 100,
FibonacciSequence simple (i) println
)
@stevedekorte
Copy link

Couldn't resist a few more changes:

Fibonacci := Object clone do(
cache := Map clone atPut("0", 1) atPut("1", 1)
at := method(n, cache atIfAbsentPut(num asString, at(n-1) + at(n-2)))
)

for (i, 1, 100,
Fibonacci at(i) println
)

@seiffert
Copy link
Author

Nice, that's a really compact and still readable solution. I'm already a big fan of IO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment