var sum = function(a, b) { return a + b; }
alert(sum(15, 2));
Notice that, in the PHP example, the semicolon is mandatory after defining the lambda function:
<?php
$lambda = function($a, $b) {
return $a + $b;
};
echo 'Sum='.$lambda(5,2);
?>
The output is:
Sum=7
Next is also a simple example of lambda function that outputs square(15):
<?php
$square = function($x) {
return $x * $x;
};
echo 'Result='.$square(15);
?>
The output is:
Result=225
Recursive Lambda Functions in PHP
In this section we will create recursive lambda functions as factorial, a sum of a given number of consecutive terms and the Fibonacci function. For creating recursive lambda function we will use Y-combinator. In computer science, a fixed-point combinator is ahigher-order function y that satisfies the equation. A combinator is a particular type ofhigher-order function that may be used in defining functions without using variables. The combinators may be combined to direct values to their correct places in the expression without ever naming them as variables." You can learn and understand more about Y-combinator < href="http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator" target="new">here.
First application returns a factorial number:
<?php
$factorial = function( $n ) use ( &$factorial ) {
if( $n == 1 ) return 1;
return $factorial( $n - 1 ) * $n;
};
print 'Factorial='.$factorial( 8 );
?>
The output is:
Factorial = 40320
Next application calculates the first n consecutives number sum, in our case 1+2+3+…+23:
<?php
$recursive_sum = function( $n ) use ( &$recursive_sum ) {
if( $n == 0 ) {$var = 0; return 0;}
return $recursive_sum( $n - 1 ) + $n;
};
print 'The recursive sum: 1+2+3+…+23 = '.$recursive_sum(23);
?>
The output is:
The recursive sum: 1+2+3+…+23 = 276
And the last application from this section is the Fibonacci:
<?php
$fibonacci = function($n)use(&$fibonacci)
{
if($n == 0 || $n == 1) return 1;
return $fibonacci($n - 1) + $fibonacci($n - 2);
};
print 'Fibonacci result is = '.$fibonacci(9);
?>
The output is:
Fibonacci result is = 55
<?php
class Test {
public $A;
}
$B = new Test();
$B->A = function(){echo('Hello World!');};
call_user_func($B->A);
?>
Outputs: Hello World!
0 comments:
Post a Comment