Chinaunix首页 | 论坛 | 博客
  • 博客访问: 131255
  • 博文数量: 36
  • 博客积分: 155
  • 博客等级: 入伍新兵
  • 技术积分: 282
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-27 20:57
文章分类

全部博文(36)

文章存档

2014年(1)

2013年(21)

2012年(15)

分类: PERL

2013-04-04 21:58:59

参考C++程序设计8.4.1使用Moose改写,特别使用Moose::Role 定义统一interface。

  1. package Role::InternalAlgo;
  2. use Moose::Role;

  3. has [ 'left', 'right' ] => (
  4.     is => 'rw',
  5.     isa => 'Num',
  6.     required => 1,
  7. );
  8. has 'steps' => (
  9.     is => 'rw',
  10.     isa => 'Int',
  11.     required => 1,
  12. );
  13. has 'height' => (
  14.     is => 'ro',
  15.     isa => 'Num',
  16.     lazy => 1,
  17.     builder => '_build_height',
  18. );
  19. sub _build_height {
  20.     my $self = shift;
  21.     return ( $self->{right} - $self->{left} ) / $self->{steps};
  22. }

  23. # interface
  24. requires 'intergrate';

  25. package Role::Function;
  26. use Moose::Role;

  27. sub function { return 4 / (1 + $_[0]**2) }


  28. package RectangleAlgo;
  29. use Moose;
  30. with 'Role::InternalAlgo';
  31. with 'Role::Function';

  32. sub intergrate {
  33.     my $self = shift;
  34.     my $a = $self->left;
  35.     my $n = $self->steps;
  36.     my $h = $self->height;
  37.     my $sum = 0;
  38.     for ( my $i = 1; $i <= $n; $i++ ) {
  39.         $a += $h;
  40.         $sum += function($a);
  41.     }
  42.     return $sum * $h;
  43. }

  44. package LadderAlgo;
  45. use Moose;
  46. with 'Role::InternalAlgo';
  47. with 'Role::Function';

  48. sub intergrate {
  49.     my $self = shift;
  50.     my $a = $self->left;
  51.     my $b = $self->right;
  52.     my $n = $self->steps;
  53.     my $h = $self->height;
  54.     my $sum = ( function($a) + function($b) ) / 2;
  55.     for ( my $i = 1; $i < $n; $i++, ) {
  56.         $a += $h;
  57.         $sum += function($a);
  58.     }
  59.     return $sum * $h;
  60. }

  61. package SimpsonAlgo;
  62. use Moose;
  63. with 'Role::InternalAlgo';
  64. with 'Role::Function';

  65. sub intergrate {
  66.     my $self = shift;
  67.     my $a = $self->left;
  68.     my $b = $self->right;
  69.     my $n = $self->steps;
  70.     my $h = $self->height;
  71.     my $sum = function($a) + function($b);
  72.     my $s = 1;
  73.     for ( my $i = 1; $i < $n; $i++ ) {
  74.         $a += $h;
  75.         $sum += ( 3 + $s ) * function($a);
  76.         $s = -$s;
  77.     }
  78.     return $sum *= $h /= 3 ;
  79. }

  80. package main;
  81. my $r = RectangleAlgo->new( left => 0, right => 1, steps => 10 );
  82. my $l = LadderAlgo->new( left => 0, right => 1, steps => 10 );
  83. my $s = SimpsonAlgo->new( left => 0, right => 1, steps => 10 );
  84. print $r->intergrate, "\n";
  85. print $l->intergrate, "\n";
  86. print $s->intergrate, "\n";

阅读(1310) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~