Skip to content

Instantly share code, notes, and snippets.

@googya
Last active September 5, 2017 08:20
Show Gist options
  • Select an option

  • Save googya/2c5818472b5f392f15cd7c4fda7795d2 to your computer and use it in GitHub Desktop.

Select an option

Save googya/2c5818472b5f392f15cd7c4fda7795d2 to your computer and use it in GitHub Desktop.
const curry = require('ramda').curry
var Monad = function(type, defs) {
for (name in defs){
type.prototype[name] = defs[name];
}
return type;
};
function Left(value){
this.value = value
}
function Right(value){
this.value=value;
}
Monad(Right, {
bind:function(fn){
return fn(this.value)
}
})
Monad(Left, {
bind: function(fn){
return this;
}
})
either = function(left, right, either){
if(either.constructor.name === 'Right')
return right(either.value)
else
return left(either.value)
}
var land = curry(function(lr, n, pole){
pole[lr] = pole[lr] + n;
if(Math.abs(pole[0]-pole[1]) > 3) {
return new Left("dead when land " + n + " became " + pole);
}
return new Right(pole);
});
var landLeft = land(0)
var landRight = land(1);
var stillAlive = function(x){
console.log(x)
}
var dead = function(x){
console.log('皮尔斯' + x);
}
var walkInLine = new Right([0,0]);
eitherDeadOrNot = walkInLine.bind(landLeft(2)).bind(landRight(5))
either(dead, stillAlive, eitherDeadOrNot)
// => [2,5]
eitherDeadOrNot = walkInLine.bind(landLeft(2)).bind(landRight(5)).bind(landLeft(3)).bind(landLeft(10).bind(landRight(10)))
either(dead, stillAlive, eitherDeadOrNot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment