Skip to content

Instantly share code, notes, and snippets.

@mhull
Created May 9, 2017 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhull/7f0a66e357677749b7367ca07de94946 to your computer and use it in GitHub Desktop.
Save mhull/7f0a66e357677749b7367ca07de94946 to your computer and use it in GitHub Desktop.
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