in reply to PERLISP meditations
Thats what you want?
my $sq = sub { $_[0]**2 }; my $id = sub { $_[0] }; sub sum { my ($a,$b,$func) =@_; $func //= $id; my $sum; $sum += $func->($_) for ($a..$b); return $sum; } sub sum_sq{ sum($_[0],$_[1],$sq)} $,=","; print sum(3,5),sum_sq(3,5); # 12,50
I skipped the &next sub for integer stepping, but shouldn't be to difficult with a while loop checking $a<$b.
(UPDATE: I'm puzzled... if "&next" is necessary to get the next element of an iterator one must also provide a &cmp for checking $a<$b in the loop-condition)
Better avoid Lisp-recursion in Perl, when you can use "real" loops, we don't automatically optimize them to loops like Lisp does.
Cheers Rolf
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: PERLISP meditations
by protist (Monk) on Sep 29, 2012 at 15:03 UTC | |
by LanX (Saint) on Sep 29, 2012 at 15:14 UTC | |
by protist (Monk) on Sep 29, 2012 at 15:46 UTC |
In Section
Meditations