The fibnonacci sequence implemented as a method on an autoboxed integer/scalar class, with caching, for demonstration purposes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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