Created
December 17, 2010 23:08
-
-
Save sbisbee/745878 to your computer and use it in GitHub Desktop.
First-class functions in PHP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* A demonstration of first-class functions in PHP. | |
* Blog post: http://www.sbisbee.com/blog.php?id=2352301864 | |
* | |
* By Sam Bisbee <www.sbisbee.com> on 2010-12-17 | |
*/ | |
function makeLouder($fn) | |
{ | |
return function($a) use($fn) { | |
return $fn($a)."!!!"; | |
}; | |
} | |
$foo = makeLouder(abs); | |
echo "<p>".$foo(900)."<br/>".$foo(-900); | |
$bar = makeLouder(strtoupper); | |
echo "<p>".$bar("upper"); | |
function makeDerivative($fn, $deltaX) | |
{ | |
return function($x) use ($fn, $deltaX) { | |
return ($fn($x + $deltaX) - $fn($x)) / $deltaX; | |
}; | |
} | |
$cos = makeDerivative(sin, 0.00000001); | |
echo "<p>".$cos(0); // 1 | |
echo "<p>".$cos(pi() / 2); // 0 | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment