Nested function: Difference between revisions
Content deleted Content added
Lua |
Thundergnat (talk | contribs) Mark as draft, move reference link to top |
||
Line 1: | Line 1: | ||
{{draft task}} |
|||
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. |
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 <tt>MakeList</tt> or <tt>makeList</tt> generate the following text: |
The following examples for <tt>MakeList</tt> or <tt>makeList</tt> generate the following text: |
||
Line 55: | Line 61: | ||
print(makeList(". ")) |
print(makeList(". ")) |
||
</lang> |
</lang> |
||
== References == |
|||
⚫ |
Revision as of 18:53, 17 September 2016
Nested function is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
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.
See: Wikipedia: Nested function article.
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");
}
Console.WriteLine(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");
}
console.log(makeList(". ")); </lang>
Lua
<lang lua> function makeList(separator)
local counter = 1
local function makeItem(item) return counter .. separator .. item .. "\n" end
return makeItem("first") .. makeItem("second") .. makeItem("third")
end
print(makeList(". ")) </lang>