参考C++程序设计8.4.1使用Moose改写,特别使用Moose::Role 定义统一interface。
-
package Role::InternalAlgo;
-
use Moose::Role;
-
-
has [ 'left', 'right' ] => (
-
is => 'rw',
-
isa => 'Num',
-
required => 1,
-
);
-
has 'steps' => (
-
is => 'rw',
-
isa => 'Int',
-
required => 1,
-
);
-
has 'height' => (
-
is => 'ro',
-
isa => 'Num',
-
lazy => 1,
-
builder => '_build_height',
-
);
-
sub _build_height {
-
my $self = shift;
-
return ( $self->{right} - $self->{left} ) / $self->{steps};
-
}
-
-
# interface
-
requires 'intergrate';
-
-
package Role::Function;
-
use Moose::Role;
-
-
sub function { return 4 / (1 + $_[0]**2) }
-
-
-
package RectangleAlgo;
-
use Moose;
-
with 'Role::InternalAlgo';
-
with 'Role::Function';
-
-
sub intergrate {
-
my $self = shift;
-
my $a = $self->left;
-
my $n = $self->steps;
-
my $h = $self->height;
-
my $sum = 0;
-
for ( my $i = 1; $i <= $n; $i++ ) {
-
$a += $h;
-
$sum += function($a);
-
}
-
return $sum * $h;
-
}
-
-
package LadderAlgo;
-
use Moose;
-
with 'Role::InternalAlgo';
-
with 'Role::Function';
-
-
sub intergrate {
-
my $self = shift;
-
my $a = $self->left;
-
my $b = $self->right;
-
my $n = $self->steps;
-
my $h = $self->height;
-
my $sum = ( function($a) + function($b) ) / 2;
-
for ( my $i = 1; $i < $n; $i++, ) {
-
$a += $h;
-
$sum += function($a);
-
}
-
return $sum * $h;
-
}
-
-
package SimpsonAlgo;
-
use Moose;
-
with 'Role::InternalAlgo';
-
with 'Role::Function';
-
-
sub intergrate {
-
my $self = shift;
-
my $a = $self->left;
-
my $b = $self->right;
-
my $n = $self->steps;
-
my $h = $self->height;
-
my $sum = function($a) + function($b);
-
my $s = 1;
-
for ( my $i = 1; $i < $n; $i++ ) {
-
$a += $h;
-
$sum += ( 3 + $s ) * function($a);
-
$s = -$s;
-
}
-
return $sum *= $h /= 3 ;
-
}
-
-
package main;
-
my $r = RectangleAlgo->new( left => 0, right => 1, steps => 10 );
-
my $l = LadderAlgo->new( left => 0, right => 1, steps => 10 );
-
my $s = SimpsonAlgo->new( left => 0, right => 1, steps => 10 );
-
print $r->intergrate, "\n";
-
print $l->intergrate, "\n";
-
print $s->intergrate, "\n";
阅读(1316) | 评论(0) | 转发(0) |