Muhammad Umer
Muhammad Umer

Reputation: 18097

Could someone explain me how this simple function works

From http://www.dartlang.org/language-tour/#functions:

Function makeAdder(num n) {
  return (num i) => n + i;
}

main() {
  var add2 = makeAdder(2);
  print(add2(3)); // 5
}

Could you translate this into english....

what is bothering me is not understanding how it works, and it works..

should it be like this var add2 = makeAdder; and then at print(add2(3)); but then it wont work...

Upvotes: 2

Views: 189

Answers (2)

AKX
AKX

Reputation: 168913

Translating this to JavaScript syntax -- hope this helps:

function makeAdder(n) {
  // Returns a new function (closure) that captures the local variable `n`, as
  // it was passed to this function. So if `n` is 10, this function essentially
  // becomes function(i) { return 10 + i; };.
  return function(i) { return n + i; };
}

function main() {
  // add2 is now a function that adds 2 to its given argument.
  var add2 = makeAdder(2); 
  print(add2(3)); // 5 is passed to add2 -- the result is 2 + 3 = 5.
}

Upvotes: 3

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

Each call to makeAdder(num n) creates and returns a new function, defined by lambda expression -- (num i) => n + i. The n is declared with madeAdder, while i with the lambda expression.

With this, makeAdder(2) essentially returns the new function (num i) => 2 + i, which is set as the value of add2.

This is then called as add2(3), which evaluates n + i as 2 + 3, resulting in 5.


This is also an example of currying:

madeAdder(2)(3); // 5

Upvotes: 2

Related Questions