Skip to content

Instantly share code, notes, and snippets.

@schwern
Created April 2, 2014 20:49
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/9942847 to your computer and use it in GitHub Desktop.
Save schwern/9942847 to your computer and use it in GitHub Desktop.
The fibnonacci sequence implemented as a method on an integer class, with caching, for demonstration purposes.
#!/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;
# Store the number
has integer =>
is => 'ro',
isa => 'Int',
default => 0;
# Store the result of fibonacci for this integer
has fibonacci =>
is => 'ro',
isa => 'Int',
lazy => 1,
builder => '_build_fibonacci';
# Allow Integer->new( $num ) to work
# along with Integer->new( integer => $num )
method BUILDARGS($class:...) {
if( @_ == 1 ) {
return { integer => shift };
}
else {
return { @_ };
}
}
method as_integer(...) {
return $self->{integer};
}
method _build_fibonacci {
return 0 if $self == 0;
return 1 if $self == 1;
return $self->new($self-1)->fibonacci + $self->new($self-2)->fibonacci;
}
__PACKAGE__->meta->make_immutable;
}
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