Okay, I wasted way too much time playing with this. First, it always bugs me when people reinvent perl's bulitins, and perl already has ranges:
sub integrate(&@)
{
local $x;
my $sum;
my $f = shift;
my %o = (from => 0, by => 0.01, @_);
for ($o{from} / $o{by} .. $o{to} / $o{by}) {
$x = $_ * $o{by};
$sum += &$f * $o{by};
}
$sum;
}
#> integrate { $x } from => 0, to => 1
## 0.505
And then I thought "why not make this multidimensional?
sub integrate(&@)
{
my $f = shift;
## Set up some sensical defaults for ranges and vars:
my ($from, $to, $by, $vars) = do {
my %o = @_;
for (qw(from to by vars)) {
$o{$_} = [$o{$_}] if exists $o{$_} && ! ref $o{$_};
}
my $dim = @{$o{from}};
$o{vars} = [qw(x y z w)[0..$dim-1]] unless $o{vars};
$o{from} = [(0) x $dim] unless $o{from};
$o{by} = [(0.01) x $dim] unless $o{by};
@o{qw(from to by vars)};
};
my $vol = 1;
$vol *= $_ for @$by;
## Generate nested evaluation loops:
local *intgen = sub {
my ($n, $body) = @_;
if ($n < 0) {
'$sum += &$f * ' . $vol;
} else {
my ($by, $v) = ($by->[$n], $vars->[$n]);
my ($lo,$hi) = ($from->[$n] / $by, $to->[$n] / $by);
"for \$$v ($lo .. $hi) { \$$v *= $by ;\n"
. intgen($n-1)
. "\n}\n";
}
};
## Do it:
(eval 'sub { my $f = shift; my $sum = 0;'.intgen($#{$from}).' $sum
+ }')
->($f);
}
#> integrate { $x * $y } from => [0,0], to => [1,1]
## 0.255025
Lightly tested, and does no error checking, but it was fun to build.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.