Search code examples
phpschemehigher-order-functionssicp

Procedures as Arguments in php


I'm learning sicp 1.3(Formulating Abstractions with Higher-Order Procedures).The scheme code can compute the sum of the cubes of the integers from a to b.

(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))
(define (inc n) (+ n 1))
(define (cube x) (* x x x))
(define (sum-cubes a b)
  (sum cube a inc b))

And i want to do it by php,here is the code.

function sum($term,$a,$next,$b){
    if ($a>$b){
        return 0;
    }else{
        return $term($a) + sum($term,$next($a),$next,$b);
    }
}
function inc($n){
    return $n + 1;
}
function cube($x){
    return $x*$x*$x;
}
function sum_cubes($a,$b){
    return sum(cube,$a,inc,$b);   // line 15
}

it works,but i received

PHP Notice: Use of undefined constant cube - assumed 'cube' in Command line code on line 15 PHP Notice: Use of undefined constant inc - assumed 'inc' in Command line code on line 15.

Is it ok and any better way to achieve it?


Solution

  • Your implementation is a little incomplete.

    'cube'($x) is valid PHP, but not really a good way to call a function in PHP. (It's also really scary that it even works.)

    By using call_user_func, you can successfully apply any callable

    function sum($term, $a, $next, $b) {
      if ($a > $b)
        return 0;
      else
        return call_user_func($term, $a)
          + sum($term, call_user_func($next, $a), $b);
    }