Created
January 19, 2016 00:29
-
-
Save dmsnell/217b4829a1bfb20599a1 to your computer and use it in GitHub Desktop.
Creating an instance of a type class in 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
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