无法在PHP中实现SICP平均阻尼

无法在PHP中实现SICP平均阻尼,php,lambda,sicp,Php,Lambda,Sicp,我在看SICP 2a讲座: 大约32:30杰拉尔德·杰伊·苏斯曼介绍了平均阻尼程序。它接受一个过程并返回一个过程,返回其参数和应用于该参数的第一个过程的平均值。在方案中,它如下所示: (define average-damp (lambda (f) (lambda (x) (average (f x) x)))) 我决定用PHP重写它: function average_damp($f) { return function ($x) {

我在看SICP 2a讲座:

大约32:30杰拉尔德·杰伊·苏斯曼介绍了平均阻尼程序。它接受一个过程并返回一个过程,返回其参数和应用于该参数的第一个过程的平均值。在方案中,它如下所示:

(define average-damp
  (lambda (f)
    (lambda (x) (average (f x) x))))
我决定用PHP重写它:

function average_damp($f)
{
      return function ($x)
      {
            $y = $f($x);//here comes the error - $f undefined
            return ($x + $y) / 2;
      };
}
然后尝试了一个简单的程序:

function div_by2($x)
{
      return $x / 2;
}

$fun = average_damp("div_by2");

$fun(2);
这个函数的平均值应该在2到2/2=2+1/2=3/2之间

但是$f在内部过程中未定义,给出了一个错误:

PHP Notice:  Undefined variable: f on line 81
PHP Fatal error:  Function name must be a string on line 81

如何修复?

您需要让返回的函数知道已传递的$f-此处的关键字是use

function average_damp($f)
{
      return function ($x) use($f) {
            $y = $f($x);
            return ($x + $y) / 2;
      };
}

主要是javascript,但也包括与PHP的不同之处

您需要让返回的函数知道传递的$f-这里的关键字是use

function average_damp($f)
{
      return function ($x) use($f) {
            $y = $f($x);
            return ($x + $y) / 2;
      };
}
主要是javascript,但也包括与PHP的区别