sum(2)(3);
? And mention other conventional equivalent of this call ?The sum function for both this call can be created like the following code
function sum(x) {
if (arguments.length == 2) {
return arguments[0] + arguments[1];
} else {
return function(y) { return x + y; };
}
}
console.log(sum(2,3)); // Outputs 5
console.log(sum(2)(3)); // Outputs 5
Depends on the context, both methods are equally important, though I would guess that the latter form is used less. When to use one over the other? Simple, if you need to pass arguments that are immediately accessible, use the first form. If one of the arguments does not change and the caller expects a function, use the second form. Consider this code, I believe it clearly illustrates my point:
function add_direct(a, b) {
return a + b;
}
function add_functor(a) {
return function (b) {
return a + b;
}
}
var nums = [1,4,8];
var add3 = add_functor(3);
console.log(nums.map(add3));
console.log(nums.map(n => {
return add_direct(3, n);
}));
They both add 3, but the second form makes sense here. Both have their strengths and weaknesses. Hopefully, this clears up the air.
PS: In C++, the second form is called a Functor; Others call them closures or Function objects.
array mapping
is slower than functor if we use an edge case of Rafael's example above.“morphisms between categories”
i.e a functor is an entity that defines the behavior of "fmap
" that, given a value and function "morphism
", maps said function onto a value of certain type "category
" and generates a new functor.
So an array is a Functor, because the array can be mapped over.Simply put, a functor is a value (an object in javascript) that:
You can find some basic examples here and here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With