Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active December 20, 2015 21: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 OliverJAsh/6201146 to your computer and use it in GitHub Desktop.
Save OliverJAsh/6201146 to your computer and use it in GitHub Desktop.
An example of currying and partial application
// Manual currying (no abstraction; right to left)
function prop(key) {
return function (object) {
return object[key]
};
}
var nameProp = prop('name');
[ { name: 'Bob' } ].map(nameProp);
// Currying (right to left)
function curry2(fun) {
return function(arg2) {
return function(arg1) {
return fun(arg1, arg2);
};
};
}
function prop(object, key) {
return object[key]
}
var nameProp = curry2(prop)('name');
[ { name: 'Bob' } ].map(nameProp);
// Manual partial application (no abstraction; right to left)
function prop(key) {
return function () {
var object = arguments[0];
return object[key];
};
}
var nameProp = prop('name');
[ { name: 'Bob' } ].map(nameProp);
// Partial application (left to right)
// This will only work when the partial application is done from the leftmost argument,
// because the map function will receive additional unwanted arguments. Thus, I have
// been forced to change the order of parameters inside of my `prop` function.
function prop(key, object) {
return object[key]
}
var nameProp = _.partial(prop, 'name');
[ { name: 'Bob' } ].map(nameProp);
// Partial application (right to left) with currying (right to left)
function curry(fun) {
return function(arg) {
return fun(arg);
};
}
function prop(object, key) {
return object[key]
}
// We need to curry our partially applied function, because `map` provides unwanted arguments
var nameProp = curry(_.partialRight(prop, 'name'));
[ { name: 'Bob' } ].map(nameProp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment