Skip to content

Instantly share code, notes, and snippets.

@rgantt
Created August 9, 2011 15:27
Show Gist options
  • Save rgantt/1134355 to your computer and use it in GitHub Desktop.
Save rgantt/1134355 to your computer and use it in GitHub Desktop.
anonymous recursion in php
<?php
$fibonacci = function( $n ) use ( &$fibonacci ) {
return ( $n < 2 ) ? $n : ( $fibonacci( $n - 1 ) + $fibonacci( $n - 2 ) );
};
echo $fibonacci(4); // Outputs "3" (0,1,1,2,3)
<?php
function map( $f, array $seq, array $mapped = array() ) {
if( !empty( $seq ) ) $mapped[] = $f( reset( $seq ) );
return !empty( $seq ) ? map( $f, array_slice( $seq, 1 ), $mapped ) : $mapped;
}
print_r( map( $fibonacci, range( 1, 5 ) ) ); // Maps integers to Fibs
<?php
$fibonacci = function( $n ) use ( $fibonacci ) {
return ( $n < 2 ) ? $n : ( $fibonacci( $n - 1 ) + $fibonacci( $n - 2 ) );
};
echo $fibonacci(4); // Fatal error: Function name must be a string
<?php
print_r( array_map( $fibonacci, range( 1, 5 ) ) ); // Maps integers to Fibs
<?php
echo array_reduce( array_map( $fibonacci, range( 1, 5 ) ), function($a,$b){ return $a+$b; }, 0 ); // Outputs 12
<?php
function reduce( $f, array $seq, $s = 0 ) {
$s = !empty( $seq ) ? $f( $s, reset( $seq ) ) : $s;
return !empty( $seq ) ? reduce( $f, array_slice( $seq, 1 ), $s ) : $s;
}
echo reduce( function($a,$b){ return $a+$b; }, map( $fibonacci, range( 1, 5 ) ), 0 ); // Outputs 12
<?php
$fibonacci = function( $n ) {
return ( $n < 2 ) ? $n : ( $fibonacci( $n - 1 ) + $fibonacci( $n - 2 ) );
};
echo $fibonacci(4); // should be (0,1,2,3,4) -> (0,1,1,2,3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment