The fibnonacci sequence implemented as a method on an integer 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 | |
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