Skip to content

Instantly share code, notes, and snippets.

@unbug
Last active May 26, 2016 10:42
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 unbug/f9632e48fb2713e9f780c679e24ec19d to your computer and use it in GitHub Desktop.
Save unbug/f9632e48fb2713e9f780c679e24ec19d to your computer and use it in GitHub Desktop.
function identity(x){
return x;
}
function add(a, b){
return a+b;
}
function mul(a, b){
return a*b;
}
function identityf(x){
return function(){
return x;
}
}
function addf(x){
return function(y){
return x+y;
}
}
function applyf(func){
return function(x){
return function(y){
return func(x, y);
}
}
}
function curry(func, a){
return function(b){
return func(a, b);
}
}
curry(function(a, b){ return a*b;}, 5)(6);
//1
inc = addf(1);
inc(5);
//2
inc = applyf(add)(1);
inc(5);
//3
inc = curry(add, 1)
inc(5);
function methodize(func){
return function(n){
return func.call(null, this, n);
}
};
Number.prototype.add = methodize(add);
(3).add(4);
function demethodize(func){
return function(that, b){
return func.call(that, b);
}
}
demethodize(Number.prototype.add)(5, 6);
function twice(func){
return function(x){
return func.call(null, x, x);
}
}
var double = twice(add);
double(11);
var square = twice(mul);
square(11);
function composeu(func1, func2){
return function(x){
return func2(func1(x));
}
}
composeu(double, square)(3);
function composeb(func1, func2){
return function(a, b, c){
return func2(func1(a, b), c);
}
}
composeb(add, mul)(2, 3, 5);
function once(func){
return function(){
var f = func;
func = null;
return f.apply(this, arguments);
}
}
var add_once = once(add);
add_once(3, 4);
//add_once(3, 4);
function counterf(n){
return {
inc: function(){
n += 1;
return n;
},
dec: function(){
n -= 1;
return n;
}
}
}
var counter = counterf(10);
counter.inc();
counter.dec();
function alert(n){
return n;
}
function revocable(nice){
return {
invoke: function(){
return nice.apply(this, arguments);
},
revoke: function(){
func = null;
}
}
}
var tmp = revocable(alert);
tmp.invoke(7);
tmp.revoke(7);
//tmp.invoke(8);
//1
function MONAD(){
return function unit(value){
var monad = Object.create(null);
monad.bind = function(){
return func(value);
}
return monad;
}
}
//2
function MONAD(){
var prototype = Object.create(null);
return function unit(value){
var monad = Object.create(prototype);
monad.bind = function(func, args){
return func.apply( undefined, [value].concat(Array.prototype.slice.apply(args || [])) );
}
return monad;
}
//1
unit.method = function(name, func){
prototype[name] = func;
return unit;
}
//2
unit.lift = function(name, func){
prototype[name] = function(args){
return unit(
this.bind( func, [value].concat(Array.prototype.slice.apply(args || [])) )
);
}
}
return unit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment