Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Examples of function composition using PHP and JavaScript
<?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
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
You can’t perform that action at this time.