Nested function

From Rosetta Code
Revision as of 10:36, 17 September 2016 by rosettacode>Roland Illig (Examples for nested functions)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

In many languages, functions can be nested, so there are outer functions and inner functions. The inner function can then access the variables of the outer function. In most languages, the inner function can also modify variables from the outer function.

The following examples for MakeList or makeList generate the following text:

1. first
2. second
3. third

C#

<lang csharp> string MakeList(string separator) {

   var counter = 1;
   var makeItem = new Func<string, string>((item) => {
       return counter++ + separator + item + "\n";
   });
   return makeItem("first") + makeItem("second") + makeItem("third");

}

var list = MakeList(". "); </lang>

JavaScript

<lang javascript> function makeList(separator) {

 var counter = 1;
 function makeItem(item) {
   return counter++ + separator + item + "\n";
 }
 return makeItem("first") + makeItem("second") + makeItem("third");

} </lang>

References