Skip to content

Instantly share code, notes, and snippets.

@es
Created December 8, 2013 20:55
Show Gist options
  • Save es/7863691 to your computer and use it in GitHub Desktop.
Save es/7863691 to your computer and use it in GitHub Desktop.
Implementation of Curry, Uncurry, & Compose functions (with accompanying tests).
/*
* Curry takes a two argumented function and returns one func that returns a second func that each take one argument.
*/
function curry (func) {
return function (x) {
return function (y) {
return func (x, y);
};
};
}
/*
* Uncurry binds a curry-ed function into one that takes two arguements
*/
function uncurry (func) {
return function (x, y) {
return func (x) (y);
};
}
/*
* Compose takes two functions and composes them just as one would compose to functions in math
*/
function compose (f, g) {
return function (x) {
return f (g (x));
};
}
/*
* Basic Tests using Chrome Dev Console
*/
console.assert ((curry (add) (1) (2)) === 3);
console.assert ((curry (multiply) (1) (2)) === 2);
console.assert ((curry (subtract) (1) (2)) === -1);
console.assert ((curry (divide) (1) (2)) === 0.5);
console.assert (((uncurry (curry (add))) (1, 2)) === add (1, 2));
console.assert (((uncurry (curry (multiply))) (1, 2)) === multiply (1, 2));
console.assert (((uncurry (curry (subtract))) (1, 2)) === subtract (1, 2));
console.assert (((uncurry (curry (divide))) (1, 2)) === divide (1, 2));
console.assert (compose (curry (multiply) (2), curry (add) (3)) (2) === 10);
console.assert (compose (curry (multiply) (2), curry (add) (5)) (3) === 16);
console.assert (compose (curry (multiply) (2), curry (multiply) (3)) (2) === 12);
console.assert (compose (curry (multiply) (2), curry (add) (5)) (2) === 14);
/*
* Helper tester functions
*/
var add = function (x, y) {
return x + y;
};
var subtract = function (x, y) {
return x - y;
};
var multiply = function (x, y) {
return x * y;
};
var divide = function (x, y) {
return x / y;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment