mvaline has asked for the wisdom of the Perl Monks concerning the following question:
I'm working through the wonderful textbook Structure and Interpretation of Computer Programs and am trying to use some of what I'm learning in Perl instead of LISP.
One of the powerful things that LISP can do is accept procedures as arguments. This gives the programmer a lot of flexibility. The example given in SICP is that of the summation (think sigma notation). Using LISP, it is possible to model summation independently of the particular series being summed. Instead of writing individual summation procedures like this:
(define (sum-integers a b) (if (> a b) 0 (+ a (sum-integers (+ a 1) b))))
and this:
(define (sum-cubes a b) (if (> a b) 0 (+ (cube a) (sum-cubes (+ a 1) b))))
You can write something like this:
(define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b))))
and use it like this:
(define (inc n) (+ n 1)) (define (sum-cubes a b) (sum cube a inc b))
Now I easily write summation procedures in Perl like this:
sub sum_integers { my ($a, $b) = @_; if ($a > $b) { return(0); } else { return( $a + &sum_integers(($a + 1), $b) ); } } sub cube { my ($a) = @_; return( $a * $a * $a ); } sub sum_cubes { my ($a, $b) = @_; if ($a > $b) { return(0); } else { return( &cube($a) + &sum_cubes(($a + 1), $b) ); } }
But what I want to do is something like this:
sub sum { my ($term, $a, $next, $b) = @_; if ($a > $b) { return(0); } else { return( $term($a) + &sum( $term, ($next($a)), ($next($b)) ) + ); } } sub inc { my ($n) = @_; return( $n + 1 ); } sub sum_cubes2 { my ($a, $b) = @_; return( &sum(&cube, $a, &inc, $b) ); }
But I can't figure out how to use a subroutine once I pass it to another subroutine. I know I'm passing the address of a subroutine using the &subroutine construct, but how do I run it when the reference to it is being stored in a scalar variable (i.e. the $term and $next variables in the sum subroutine above) ?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Passing subroutines as arguments
by chip (Curate) on May 08, 2003 at 19:45 UTC | |
by mvaline (Friar) on May 08, 2003 at 20:11 UTC | |
by arturo (Vicar) on May 08, 2003 at 20:24 UTC | |
by mvaline (Friar) on May 08, 2003 at 20:37 UTC | |
Re: Passing subroutines as arguments
by dws (Chancellor) on May 08, 2003 at 19:46 UTC | |
by dragonchild (Archbishop) on May 08, 2003 at 19:53 UTC | |
by dws (Chancellor) on May 08, 2003 at 20:01 UTC | |
by linux454 (Pilgrim) on May 09, 2003 at 14:03 UTC | |
Re: Passing subroutines as arguments
by dpuu (Chaplain) on May 08, 2003 at 19:47 UTC | |
Re: Passing subroutines as arguments
by hv (Prior) on May 08, 2003 at 19:56 UTC | |
Re: Passing subroutines as arguments
by dragonchild (Archbishop) on May 08, 2003 at 20:39 UTC | |
Sum of two cubes....
by Mr. Muskrat (Canon) on May 08, 2003 at 20:09 UTC | |
Re: Passing subroutines as arguments
by @ncientgoose (Novice) on May 09, 2003 at 03:23 UTC |