Skip to content

Instantly share code, notes, and snippets.

@dmsnell
Created January 19, 2016 00:29
Show Gist options
  • Save dmsnell/217b4829a1bfb20599a1 to your computer and use it in GitHub Desktop.
Save dmsnell/217b4829a1bfb20599a1 to your computer and use it in GitHub Desktop.
Creating an instance of a type class in JavaScript
const l = m => console.log( m );
function Maybe(v) {
this.value = v
}
Maybe.prototype.typeName = 'Maybe'
function Monad() {
this.value = null
}
Monad.prototype.mbind = function() { return this }
Monad.prototype.mreturn = function() { return this.value }
function Instance( BaseType, InstanceType, instanceMethods ) {
Object.keys( BaseType.prototype )
.filter( methodName => 'function' === typeof BaseType.prototype[ methodName ] )
.forEach( methodName => {
InstanceType.prototype[ methodName ] = instanceMethods[ methodName ]
} )
}
Instance( Monad, Maybe, {
mbind( f ) { return this.value ? new Maybe( f( this.value ) ) : this },
mreturn() { return this.value }
} )
const just3 = new Maybe( 3 )
const nothing = new Maybe( null )
l( just3.mreturn() )
l( nothing.mreturn() )
l( just3.mbind( a => 2 * a ).mreturn() )
l( nothing.mbind( a => 2 * a ).mreturn() )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment