Skip to content

Instantly share code, notes, and snippets.

@schwern
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schwern/9942770 to your computer and use it in GitHub Desktop.
Save schwern/9942770 to your computer and use it in GitHub Desktop.
The fibnonacci sequence implemented as a method on an autoboxed integer/scalar class, with caching, for demonstration purposes.
#!/usr/bin/perl
# This turns on function signatures and autoboxing
# amongst a lot of other things.
use perl5i::2;
# This class adds methods callable on all scalar variables.
{
package SCALAR;
use perl5i::2;
method fibonacci {
# This cache is attached to the fibnoacci method.
# It is initialized only once.
state $cache = {
0 => 0,
1 => 1
};
return $cache->{$self} //= ($self-1)->fibonacci + ($self-2)->fibonacci;
}
}
say 20->fibonacci;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment