Skip to content

Instantly share code, notes, and snippets.

@philopon
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save philopon/61e66152d21797dca94c to your computer and use it in GitHub Desktop.

Select an option

Save philopon/61e66152d21797dca94c to your computer and use it in GitHub Desktop.
// data Maybe a = Just a | Nothing
var Maybe = function(){}
// type: reserved keyword in haskell
Maybe.type = {
Just: function(_0){this._0 = _0;},
Nothing: function(){}
}
Maybe.type.Just.prototype = Object.create(Maybe.prototype);
Maybe.type.Just.prototype.constructor = Maybe.type.Just;
Maybe.type.Nothing.prototype = Object.create(Maybe.prototype);
Maybe.type.Nothing.prototype.constructor = Maybe.type.Nothing;
// class method:
// * unqualified: data constructor
// * qualified: instance method(first argument /= self type)
Maybe.Just = function(a){return new Maybe.type.Just(a)};
Maybe.Nothing = new Maybe.type.Nothing;
// instance method: instance method(first argument == self type)
// class Show a where
// show [toString] :: a -> String
//
// instance Show a => Show (Maybe a) where
// show (Just a) = "Just " ++ show a;
// show _ = "Nothing"
Maybe.prototype.toString = function(){
if (this instanceof Maybe.type.Just) {
var a = this._0;
return "Just " + a.toString();
} else {
return "Nothing";
}
}
// class Monad m where
// (>>=) "bind" :: m a -> (a -> m b) -> m b
// return :: a -> m a
//
// instance Monad Maybe where
// (>>=) (Just a) f = f a
// return _ f = Nothing
Maybe.prototype.Prelude$Monad$bind = function(f){
if(this instanceof Maybe.type.Just){
return f(this._0);
} else {
return Maybe.Nothing;
}
}
Maybe.Prelude$Monad$return = Maybe.Just;
/*
a = do
a <- return 3
b <- Nothing
c <- return (b + 3)
return (c * 2)
*/
var a = (function($){
return $.Prelude$Monad.Prelude$Monad$return(3)
.Prelude$Monad$bind(function(a){
return Maybe.Nothing;
}).Prelude$Monad$bind(function(a){
return $.Prelude$Monad.Prelude$Monad$return(a + 3);
}).Prelude$Monad$bind(function(a){
return $.Prelude$Monad.Prelude$Monad$return(a * 2);
});
}({Prelude$Monad: Maybe, Prelude$Read: parseInt}));
console.log(a.toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment