Question

I was watching SICP 2a lecture:

https://www.youtube.com/watch?v=erHp3r6PbJk&list=PL8FE88AA54363BC46

around 32:30 Gerald Jay Sussman introduces AVERAGE-DAMP procedure. It takes a procedure and returns a procedure, returning an average of it's argument and the first procedure, applied to the argument. In Scheme it looks like this:

(define average-damp
  (lambda (f)
    (lambda (x) (average (f x) x))))

I decided to rewrite it in PHP:

function average_damp($f)
{
      return function ($x)
      {
            $y = $f($x);//here comes the error - $f undefined
            return ($x + $y) / 2;
      };
}

And then tried with a simple procedure:

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

$fun = average_damp("div_by2");

$fun(2);

This stuff should return an average between 2 and (2/2) = (2 + 1)/2 = 3/2.

But $f is undefined in the internal procedure, giving an error:

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

How to fix?

Was it helpful?

Solution

You need to make returned function be aware of passed $f - use is the keyword here

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

Recommended video about closure and variable scope (mainly javascript, but also includes differences from PHP)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top