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) ?
In reply to Passing subroutines as arguments by mvaline
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |