Don't like ads? PRO users don't see any ads ;-)
Guest

PHP lambdas

By: a guest on Jun 1st, 2012  |  syntax: PHP  |  size: 0.88 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. function L($expr) {
  2.     $lhelper = function($expr, $vars = array()) use (&$lhelper){
  3.         if (is_null($expr)) return;
  4.  
  5.         $parts = explode('=>', $expr, 2);
  6.  
  7.         if (!isset($parts[1])) {
  8.             $stmts = explode(';', $parts[0]);
  9.             return implode(';', array_slice($stmts, 0, -1) + array('return '. end($stmts)));
  10.         }
  11.  
  12.         return 'return function('.
  13.             $parts[0].
  14.             ')'.
  15.             ($vars ? ' use('. implode(',', $vars) .')' : '').
  16.             ' { '.
  17.             $lhelper($parts[1], ($vars + explode(',', $parts[0]))).
  18.             ';}';
  19.     };
  20.  
  21.     return eval($lhelper($expr) .';');
  22. }            
  23.  
  24. $l1 = L('$x, $f => $f($x)');
  25. $l2 = L('$x => $y => $x * $y');
  26.  
  27. echo $l1(17, $l2(17)), PHP_EOL;
  28.  
  29. $a = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17);
  30. print_r(array_map(L('$x => $x * $x'), $a));