The fibnonacci sequence implemented as a method on an immutable integer class, with purely per object 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 | |
use perl5i::2; | |
# A full on Integer class. | |
{ | |
package _Integer; | |
use perl5i::2; | |
use Method::Signatures; | |
use Mouse; | |
# Make this class act like a number. | |
use overload | |
"0+" => \&as_integer, | |
fallback => 1; | |
has integer => | |
is => 'ro', | |
isa => 'Int', | |
default => 0; | |
has fibonacci => | |
is => 'ro', | |
isa => 'Int', | |
lazy => 1, | |
builder => '_build_fibonacci'; | |
method as_integer(...) { | |
return $self->{integer}; | |
} | |
method _build_fibonacci { | |
return Integer->new($self-1)->fibonacci + Integer->new($self-2)->fibonacci; | |
} | |
__PACKAGE__->meta->make_immutable; | |
} | |
# A flyweight caching wrapper around _Integer. | |
{ | |
package Integer; | |
use perl5i::2; | |
use Method::Signatures; | |
our @ISA = qw(_Integer); | |
# A class-wide cache for _Integer objects | |
state $Object_Cache = { | |
# Seed the fibonacci sequence | |
0 => _Integer->new( integer => 0, fibonacci => 0 ), | |
1 => _Integer->new( integer => 1, fibonacci => 1 ), | |
}; | |
# Since _Integer objects are immutable, there's no need to ever make | |
# more than one for each integer. | |
method new($class: Int $int) { | |
return $Object_Cache->{$int} //= _Integer->new( integer => $int ); | |
} | |
} | |
my $num = shift; | |
my $int = Integer->new($num); | |
say $int->fibonacci; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment