Skip to content

Instantly share code, notes, and snippets.

@XuefengWu
Created January 21, 2014 16:58
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 XuefengWu/8543763 to your computer and use it in GitHub Desktop.
Save XuefengWu/8543763 to your computer and use it in GitHub Desktop.
/**
* Curry - Function currying
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
* Date: 10/4/2008
*
* @author Ariel Flesler
* @version 1.0.1
*/
function curry( fn ){
return function(){
var args = curry.args(arguments),
master = arguments.callee,
self = this;
return args.length >= fn.length ? fn.apply(self,args) : function(){
return master.apply( self, args.concat(curry.args(arguments)) );
};
};
};
curry.args = function( args ){
return Array.prototype.slice.call(args);
};
Function.prototype.curry = function(){
return curry(this);
};
Curry by Ariel Flesler
Links
Download(1.0.1)
Haskell Functions
// Check http://demos.flesler.com/Curry/js/Curry.js for the curry() function
// These are some examples of currying application
// They were also executed so you can try them on a console
// General
function compose(f, g) {
return function(x,y) {
return g(f(y))(x);
}
}
function delegate(f) {
return function(v) {
f(v)
}
}
// Math
function sum(x){
return function(y) {
x + y;
}
}
var inc = sum(1);
inc(2) //3
var dec = sum(-1);
dec(2) //1
function prod(x) {
return function(y) {
return x * y;
}
}
var negate = prod(-1);
var sub = compose(negate, sum);
var inv = function( x ){
return 1/x;
};
var div = compose(inv, prod);
// DOM
function attr(elem, key) {
return function(value) {
elem[key] = value;
}
}
var setCookie = attr(document,'cookie');
setCookie('foo=bar;');
// Arrays
function each(f) {
return function(l) {
for( var i=0; i < list.length; i++ )
f( list[i], i );
}
}
var printAll = each(function(x){console.log(x);})
var map = curry(function( f, list ){
var copy = [];
each(function(e, i){
copy[i] = f(e);
}, list );
return copy;
});
function map(f) {
return function(l) {
var copy = [];
each(function(e, i){
copy[i] = f(e);
}, l);
return copy;
}
}
//XXX
var reduce = curry(function( f, accum, list ){
each(function( e ){
return accum = f( accum, e );
}, list );
return accum;
});
function reduce(f) {
return function(accum, l) {
each(function( e ){
return accum = f( accum, e );
}, l );
return accum;
}
}
var printAll = reduce(function(acc,x) {console.log(x);})
printAll([1,2,3])
var sumAll = reduce(function(acc,x) {return acc + x;},0);
sumAll([1,2,3])
// f.e: incAll( [1,2,3] ) --> [2,3,4]
var incAll = map( inc );
var decAll = map( dec );
var doubleAll = map( prod(2) );
var alertList = each( alert );
var sumList = reduce( sum, 0 );
var concat = reduce( sum, '' );
var length = reduce( inc, 0 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment