Last active
December 20, 2015 21:58
-
-
Save OliverJAsh/6201146 to your computer and use it in GitHub Desktop.
An example of currying and partial application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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