Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript support partial function application?

Reading through the Wikipedia article on First-Class functions, there is a nice table of language support for various aspects of functional programming: http://en.wikipedia.org/wiki/First-class_function#Language_support

JavaScript is listed as not having partial function application. However, there are techniques for creating a function that returns a function that with some of the parameters stored in a closure, ie:

var add = function(a, b){
    return a + b;
},
apply = function(fn, a){
    return function(b){ 
        return fn(a, b); 
    }
},
addFive = apply(add, 5);

console.log(addFive(2)); // prints 7

Is this not partial function application? If not, could someone please provide an example of partial function application in another language and explain how it is different?

Thanks!

like image 795
Jason Suárez Avatar asked Mar 22 '12 07:03

Jason Suárez


People also ask

What is partial application in JavaScript?

Partial application allows us to fix a function's arguments. This lets us derive new functions, with specific behavior, from other, more general functions. Currying transforms a function that accepts multiple arguments “all at once” into a series of function calls, each of which involves only one argument at a time.

What is difference between currying and partial application?

Currying: A function returning another function that might return another function, but every returned function must take only one parameter at a time. Partial application: A function returning another function that might return another function, but each returned function can take several parameters.

What types of functions work with JavaScript?

There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.

How many types of functions does JavaScript support?

Functions in JavaScript are very similar to those of some other scripting high-level languages such as TypeScript and there are two types of functions: predefined and user-defined.


1 Answers

var func1 = function(a, b) {
  return a + b;
}

var func2 = func1.bind(undefined, 3);

func2(1); // 4
func2(2); // 5
func2(3); // 6

check docs at developer.mozilla.org

like image 183
Andre Avatar answered Oct 25 '22 19:10

Andre