Created
May 9, 2017 14:10
-
-
Save mhull/7f0a66e357677749b7367ca07de94946 to your computer and use it in GitHub Desktop.
Examples of function composition using PHP and JavaScript
This file contains 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 | |
function f( $x ) { | |
return $x+5; | |
} | |
function g( $x ) { | |
return $x+1; | |
} | |
function fog( $x ) { | |
return f( g( $x ) ); | |
} | |
var_dump( fog(3) ); // 9 |
This file contains 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
function f(x) { | |
return x+5; | |
} | |
function g(x) { | |
return x+1; | |
} | |
/** | |
* Returns a composite function using two given functions | |
* | |
* Note that the output of `func2` must be an appropriate input | |
* for `func1` whenever the composite function is used | |
*/ | |
function getComposition(func1, func2) { | |
return function(x) { | |
/** | |
* We need an intermediate step since, for some reason, the | |
* expression `func1(func2(x))` returns `undefined` | |
*/ | |
let placeholder = func2(x); | |
return func1( placeholder ); | |
} | |
} | |
let fog = getComposition(f, g); | |
console.log( fog(3) ); // 9 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment