6

Can someone explain how this works?

http://docs.hhvm.com/manual/en/hack.lambda.php

Variables are captured automatically and transitively (including $this):

<?hh
$z = 11;
$foo = $x ==> $y ==> $x * $z + $y;
$bar = $foo(5);
var_dump($bar(4)); // outputs 59
Paul Tarjan
  • 48,968
  • 59
  • 172
  • 213
Bob Brunius
  • 1,344
  • 5
  • 14
  • 21

1 Answers1

9

Conceptually, $foo is like a function with 2 inputs, x and y. Calling $foo is like a partial function evaluation that sets x=5. The $bar call then evaluates the function with y=4. So you end up with x * z + y = 5 * 11 + 4 = 59.

To put it another way, $foo is a lambda that evaluates to another lambda. So $bar becomes a lambda that evaluates to a number.

$z = 11

$foo = $x ==> $y ==> $x * $z + $y;
// foo = f(x,y,z) = x * z + y

$bar = $foo(5);                 // $bar is now $y ==> 5 * $z + $y
// bar = f(y,z) = 5 * z + y

$result = $bar(4);              // this gives you 5 * $z + 4 = 59
// result = f(z) = 5 * z + 4

var_dump(result);               // outputs 59
McGarnagle
  • 101,349
  • 31
  • 229
  • 260