Skip to content

Instantly share code, notes, and snippets.

@idmontie
Created August 30, 2015 16:35
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 idmontie/4c60ce5fe41ebc3ea5d5 to your computer and use it in GitHub Desktop.
Save idmontie/4c60ce5fe41ebc3ea5d5 to your computer and use it in GitHub Desktop.
Monad example in JavaScript
var cube = function ( x ) { return [x * x * x, "Cube was called"]; };
var square = function ( x ) { return [x * x, "Square was called"]; };
var compose = function ( f, g ) { return function ( a ) { return f( g( a ) ); }; };
var Debuggable = function ( f ) {
return function ( debugInfo ) {
var x = debugInfo[0],
s = debugInfo[1],
fx = f( x ),
y = fx[0],
t = fx[1];
return [ y, s + t ];
}
}
var DebuggableUnit = function ( x ) { return [ x, '' ]; }
var liftedComposition = compose( Debuggable( cube ), Debuggable( square ) );
liftedComposition( DebuggableUnit( 3 ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment