Friday, September 9, 2011

Implementation of Pascal's Triangle with Perl and Moose

Probably not the best way to do it, but I thought I would give it a hack:




#!/usr/bin/perl

package Row;

use Moose;

has triangle => (
is => 'ro',
isa => 'Triangle',
);

has prev => (
is => 'ro',
isa => 'Row',
);

has members => (
is => 'rw',
isa => 'ArrayRef[Int]',
lazy_build => 1,
);

sub _build_members {
my $self = shift;

return [1] unless $self->prev;

my @prev = @{ $self->prev->members };

my @values = (1);

for(my $i = 0; $i < ( scalar(@prev) - 1 ); $i++) {
my $c = $prev[ $i ];
my $n = $prev[ $i + 1 ] || 1;

push @values, $c + $n;
}

push @values, 1;

return \@values;
}

sub print {
my $self = shift;
print join ' ', @{ $self->members },"\n";
return $self;
}

__PACKAGE__->meta->make_immutable;

no Moose;

package Triangle;

use Moose;

has rows => (
is => 'rw',
isa => 'ArrayRef[Row]',
default => sub { [ Row->new({}) ] },
);

sub first {
my $self = shift;
return $self->rows->[0];
}

sub last {
my $self = shift;
return $self->rows->[ $#{ $self->rows } ];
}

sub next {
my $self = shift;
my $row = Row->new( prev => $self->last );
push @{ $self->rows }, $row;
return $self->last;
}

__PACKAGE__->meta->make_immutable;

package main;

die "Usage: $0 \n"
unless $ARGV[0] > 1;


my $t = Triangle->new;

$t->next->prev->print foreach(1..$ARGV[0]);

No comments:

Post a Comment