Nested function: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (Sidef comes before Simula)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(47 intermediate revisions by 24 users not shown)
Line 1:
{{task}}
[[Category:Scope]][[Category:Functions and subroutines]]
 
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
 
'''The Task'''
 
;Task:
Write a program consisting of two nested functions that prints the following text.
 
Line 15 ⟶ 16:
The inner function (called <tt>MakeItem</tt> or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
 
'''References:'''
 
;References:
:* [[wp:Nested function|Nested function]]
<br><br>
 
=={{header|11l}}==
[[Category:Scope]][[Category:Functions and subroutines]]
{{trans|Python}}
 
<syntaxhighlight lang="11l">F makeList(separator)
V counter = 1
 
F makeItem(item)
-V result = @counter‘’@separator‘’item"\n"
@counter++
R result
 
R makeItem(‘first’)‘’makeItem(‘second’)‘’makeItem(‘third’)
 
print(makeList(‘. ’))</syntaxhighlight>
 
{{out}}
<pre>
1. first
2. second
3. third
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Nested_Functions is -- 'Nested_Functions' is the name of 'main'
Line 45 ⟶ 67:
Ada.Text_IO.Put_Line(Item);
end loop;
end Nested_Functions;</langsyntaxhighlight>
{{out}}
<pre>$ ./nested_functions
Line 51 ⟶ 73:
2. Second
3. Third
</pre>
=={{header|68000 Assembly}}==
<syntaxhighlight lang="68000devpac">;program starts here, after loading palettes etc.
MOVE.W #3,D1
MOVE.W #'.',D4
 
JSR MakeList
 
jmp * ;halt
 
 
 
MakeList:
MOVE.W #1,D0
loop_MakeList:
MOVE.W D0,-(SP)
JSR PrintHex
MOVE.B D4,D0 ;load separator into D0
JSR PrintChar
MOVE.B #' ',D0
JSR PrintChar
MOVE.W (SP)+,D0
JSR MakeItem
CMP.W D0,D1
BCC loop_MakeList ;back to start
RTS
MakeItem:
MOVE.W D0,D2
SUBQ.W #1,D2
LSL.W #2,D2
LEA PointerToText,A0
MOVE.L (A0,D2),A3
JSR PrintString
JSR NewLine
ADDQ.W #1,D0
RTS
 
 
PointerToText:
DC.L FIRST,SECOND,THIRD
FIRST:
DC.B "FIRST",0
EVEN
SECOND:
DC.B "SECOND",0
EVEN
THIRD:
DC.B "THIRD",0
EVEN</syntaxhighlight>
 
{{out}}
[https://ibb.co/mqCKVGy Output running on MAME]
 
Also displayed here:
<pre>
01. FIRST
02. SECOND
03. THIRD
</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">PROC make list = ( STRING separator )STRING:
BEGIN
INT counter := 0;
Line 66 ⟶ 149:
 
print( ( make list( ". " ) ) )
</syntaxhighlight>
</lang>
 
=={{header|ALGOL W}}==
Algol W strings are fixed length which makes this slightly more complicated than the Algol 68 solution.
<langsyntaxhighlight lang="algolw">begin
string(30) procedure makeList ( string(2) value separator ) ;
begin
Line 94 ⟶ 177:
end; % makeList %
write( makeList( ". " ) )
end.</langsyntaxhighlight>
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">-- NESTED FUNCTION --------------------------------------- NESTED FUNCTION --------------------
 
-- makeList :: String -> String
Line 115 ⟶ 198:
end makeList
 
-- TEST --------------------------------------------- TEST -------------------------
on run
Line 123 ⟶ 206:
 
 
-- GENERIC FUNCTIONS -------------------------------------- GENERIC FUNCTIONS -------------------
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
Line 135 ⟶ 233:
return lst
end tell
end map</syntaxhighlight>
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn</lang>
{{Out}}
<pre>1. first
Line 156 ⟶ 242:
Note, however, that mutation creates redundant complexity and loss of referential transparency. Functions which modify values outside their own scope are rarely, if ever, necessary, and always best avoided. Simpler and sounder here to derive the incrementing index either by zipping the input list with a range of integers, or by inheriting it from the higher order map function:
 
<langsyntaxhighlight AppleScriptlang="applescript">-- makeList :: String -> String
on makeList(separator)
Line 167 ⟶ 253:
map(makeItem, ["first", "second", "third"]) as string
end makeList</langsyntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">makeList: function [separator][
counter: 1
 
makeItem: function [item] .export:[counter][
result: ~"|counter||separator||item|"
counter: counter+1
return result
]
 
@[
makeItem "first"
makeItem "second"
makeItem "third"
]
]
 
print join.with:"\n" makeList ". "</syntaxhighlight>
 
{{out}}
 
<pre>1. first
2. second
3. third</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
//
Line 208 ⟶ 319:
 
(* ****** ****** *)
</syntaxhighlight>
</lang>
 
=={{header|BQN}}==
<syntaxhighlight lang="bqn">MakeList ← {
nl←@+10 ⋄ s←𝕩 ⋄ i←0
MakeItem ← {i+↩1 ⋄ (•Fmt i)∾s∾𝕩}
(⊣∾nl∾⊢)´MakeItem¨"first"‿"second"‿"third"
}</syntaxhighlight>
 
{{out}}
<pre>
MakeList ". "
"1. first
2. second
3. third"
</pre>
 
=={{header|C}}==
Line 218 ⟶ 343:
 
'''IMPORTANT''' This implementation will only work with GCC. Go through the link above for details.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<stdio.h>
Line 256 ⟶ 381:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 264 ⟶ 389:
</pre>
 
=={{header|C++ sharp|C#}}==
<syntaxhighlight lang="csharp">string MakeList(string separator)
{{works with|C++11}}
<lang cpp>#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> makeList(std::string separator) {
auto counter = 0;
auto makeItem = [&](std::string item) {
return std::to_string(++counter) + separator + item;
};
return {makeItem("first"), makeItem("second"), makeItem("third")};
}
 
int main() {
for (auto item : makeList(". "))
std::cout << item << "\n";
}</lang>
 
=={{header|C#}}==
<lang csharp>string MakeList(string separator)
{
int counter = 1;
Line 293 ⟶ 399:
}
 
Console.WriteLine(MakeList(". "));</langsyntaxhighlight>
'''Update'''<br/>
As of C#7, we can nest actual methods inside other methods instead of creating delegate instances. They can even be declared after the return statement.
<langsyntaxhighlight lang="csharp">string MakeList2(string separator)
{
int counter = 1;
Line 303 ⟶ 409:
//using string interpolation
string MakeItem(string item) => $"{counter++}{separator}{item}\n";
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|C++11}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> makeList(std::string separator) {
auto counter = 0;
auto makeItem = [&](std::string item) {
return std::to_string(++counter) + separator + item;
};
return {makeItem("first"), makeItem("second"), makeItem("third")};
}
 
int main() {
for (auto item : makeList(". "))
std::cout << item << "\n";
}</syntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">(defn make-list [separator]
(let [x (atom 0)]
(letfn [(make-item [item] (swap! x inc) (println (format "%s%s%s" @x separator item)))]
Line 314 ⟶ 439:
(make-item "third"))))
 
(make-list ". ")</langsyntaxhighlight>
 
{{out}}
Line 325 ⟶ 450:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun my-make-list (separator)
(let ((counter 0))
(flet ((make-item (item)
Line 334 ⟶ 459:
(make-item "third")))))
 
(format t (my-make-list ". "))</langsyntaxhighlight>
 
''PS: A function named make-list is already defined in Common Lisp, see [http://www.lispworks.com/documentation/HyperSpec/Body/f_mk_lis.htm#make-list specification].''
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
 
sub MakeList(sep: [uint8], buf: [uint8]): (out: [uint8]) is
out := buf; # return begin of buffer for ease of use
var counter: uint32 := 0;
 
# Add item to string
sub AddStr(str: [uint8]) is
var length := StrLen(str);
MemCopy(str, length, buf);
buf := buf + length;
end sub;
 
sub MakeItem(item: [uint8]) is
counter := counter + 1;
buf := UIToA(counter, 10, buf);
AddStr(sep);
AddStr(item);
AddStr("\n");
end sub;
 
MakeItem("first");
MakeItem("second");
MakeItem("third");
[buf] := 0; # terminate string
end sub;
 
var buffer: uint8[100];
 
print(MakeList(". ", &buffer as [uint8]));</syntaxhighlight>
 
{{out}}
 
<pre>1. first
2. second
3. third</pre>
 
=={{header|D}}==
 
<langsyntaxhighlight lang="d">string makeList(string seperator) {
int counter = 1;
 
Line 354 ⟶ 518:
import std.stdio : writeln;
writeln(makeList(". "));
}</langsyntaxhighlight>
 
{{out}}
 
<pre>1. first
2. second
3. third</pre>
 
=={{header|Delphi}}==
''See [[#Pascal|Pascal]]''
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module NestedFunction {
static String makeList(String separator) {
Int counter = 1;
 
function String(String) makeItem = item -> $"{counter++}{separator}{item}\n";
 
return makeItem("first")
+ makeItem("second")
+ makeItem("third");
}
 
void run() {
@Inject Console console;
console.print(makeList(". "));
}
}
</syntaxhighlight>
 
{{out}}
<pre>
1. first
2. second
3. third
</pre>
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
MakeList(separator)
Line 367 ⟶ 564:
var counter := 1;
var makeItem := (item){ var retVal := counter.PrintabletoPrintable() + separator + item + (forward newLine)newLineConstant; counter += 1; ^ retVal };
^ makeItem("first") + makeItem("second") + makeItem("third")
Line 375 ⟶ 572:
{
console.printLine(MakeList(". "))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 385 ⟶ 582:
=={{header|Elixir}}==
Elixir data are immutable. Anonymous functions are closures and as such they can access variables that are in scope when the function is defined. Keep in mind a variable assigned inside a function does not affect its surrounding environment:
<langsyntaxhighlight lang="elixir">defmodule Nested do
def makeList(separator) do
counter = 1
Line 399 ⟶ 596:
end
 
IO.write Nested.makeList(". ")</langsyntaxhighlight>
 
{{out}}
<pre>
1. first
2. second
3. third
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun makeList = List by text separator
int counter = 0
fun makeItem = text by text item
return ++counter + separator + item
end
return text[makeItem("first"), makeItem("second"), makeItem("third")]
end
for each text item in makeList(". ") do writeLine(item) end
</syntaxhighlight>
{{out}}
<pre>
Line 413 ⟶ 628:
If we really wanted, we could also define a named word inside <code>make-list</code> at run time, using words such as <code>define</code> in the <code>words</code> vocabulary.
 
<langsyntaxhighlight lang="factor">USING: io kernel math math.parser locals qw sequences ;
IN: rosetta-code.nested-functions
 
Line 425 ⟶ 640:
;
". " make-list write</langsyntaxhighlight>
 
=={{header|Fōrmulæ}}==
 
In [http://wiki.formulae.org/Nested_function this] page you can see the solution of this task.
 
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
=={{header|Fortran}}==
===Arithmetic statement functions===
Fortran allows the user to define functions (and subroutines also) but from first Fortran (1958) on these are compiled as separate items and cannot themselves contain the definition of another function (or subroutine) - except for the special form allowing the definition of what is called an arithmetic statement function, such as follows:<langsyntaxhighlight Fortranlang="fortran"> FUNCTION F(X)
REAL X
DIST(U,V,W) = X*SQRT(U**2 + V**2 + W**2) !The contained function.
T = EXP(X)
F = T + DIST(T,SIN(X),ATAN(X) + 7) !Invoked...
END</langsyntaxhighlight>
This (deranged) function contains within it the definition of function DIST (which must be achieved in a single arithmetic statement), and which has access to all the variables of its containing function as well as its own parameters. The sequence <code>DIST(U,V,W) = ''etc.''</code> would normally be interpreted as an assignment of a value to an element of an array called DIST, but, no such array has been declared so this must therefore be the definition of an arithmetic statement function. Such functions are defined following any declarations of variables, and precede the normal executable statements such as <code>T = EXP(X)</code>. Since they are for arithmetic they cannot be used for character manipulations, and the CHARACTER variable only appeared with F77.
 
Line 448 ⟶ 655:
With the advent of F90 comes the CONTAINS statement, whereby within a function (or subroutine) but oddly, at its ''end'' (but before its END) appears the key word CONTAINS, after which further functions (and subroutines) may be defined in the established manner. These have access to all the variables defined in the containing routine, though if the contained routine declares a name used in the containing routine then that outside name becomes inaccessible.
 
Such contained routines are not themselves allowed to contain routines, so that the nesting is limited to two levels - except that arithmetic statement functions are available, so that three levels could be employed. Languages such as Algol, pl/i, Pascal, etc. impose no such constraint. <langsyntaxhighlight Fortranlang="fortran"> SUBROUTINE POOBAH(TEXT,L,SEP) !I've got a little list!
CHARACTER*(*) TEXT !The supplied scratchpad.
INTEGER L !Its length.
Line 480 ⟶ 687:
CALL POOBAH(TEXT,L,". ")
WRITE (6,"(A)") TEXT(1:L)
END</langsyntaxhighlight>
 
Fortran doesn't offer a "list" construction as a built-in facility so it seemed easiest to prepare the list in a CHARACTER variable. These do not have a length attribute as in a string, the LEN function reports the size of the character variable not something such as the current length of a string varying from zero to the storage limit. So, the length of the in-use portion is tracked with the aid of an auxiliary variable, and one must decide on a sufficiently large scratchpad area to hold the anticipated result. And, since the items are of varying length, the length of the whole sequence is returned, not the number of items. Subroutine POOBAH could be instead a function, but, it would have to return a fixed-size result (as in say <code>CHARACTER*66 FUNCTION POOBAH(SEP)</code>) and can't return a length as well, unless via messing with a global variable such as in COMMON or via an additional parameter as with the L above.
Line 489 ⟶ 696:
 
===When storage is abundant===
Another way of providing a "list" is via an array as in <code>CHARACTER*28 TEXT(9)</code>) so that each item occupied one element, and the maddening question "how long is a piece of string" arises twice: how much storage to allow for each element when all must be as long as the longest text expected, and, how many elements are to be allowed for.<langsyntaxhighlight Fortranlang="fortran"> SUBROUTINE POOBAH(TEXT,N,SEP) !I've got a little list!
CHARACTER*(*) TEXT(*) !The supplied scratchpad.
INTEGER N !Entry count.
Line 511 ⟶ 718:
CALL POOBAH(TEXT,N,". ")
WRITE (6,"(A)") (TEXT(I)(1:LEN_TRIM(TEXT(I))), I = 1,N)
END</langsyntaxhighlight>
The output statement could be <code>WRITE (6,"(A)") TEXT(1:N)</code> but this would write out the trailing spaces in each element. A TRIM intrinsic function may be available, but, leading spaces may be desired in the case that there are to be more than nine elements. If so, <code>FORMAT (I2,2A)</code> would be needed up to ninety-nine, or more generally, I0 format. Except that would not write out leading spaces and would spoil the neatness of a columnar layout. With file names, the lack of leading spaces (or zero digits) leads to the ideas explored in [[Natural_sorting|"Natural" sorting]]. One could define constants via the PARAMETER statement to document the linkage between the number of array elements and the correct FORMAT code, though this is messy because for NMAX elements the format code requires <Log10(NMAX) + 1> digits, and in such an attempt I've seen Log10(10) come out not as one but as 0·9999932 or somesuch, truncating to zero.
 
F95 introduced facilities whereby a string-style compound variable with both content and current length could be defined and manipulated, and when assigned to it would be reallocated storage so as to have exactly the size to hold the result. Later fortran standardised such a scheme. Similarly, one could define a data aggregate containing a count <code>N</code> as well as the <code>TEXT</code> array and a function could return such a compound entity as its result. It may also be possible to arrange that array TEXT becomes "ragged", that is, TEXT(i) is not always 28 characters long, but only as much as is needed to store the actual item.
 
=={{header|FreeBASIC}}==
 
FreeBASIC does not currently support either nested procedures or lambda expressions.
The best we can do here is to create two separate procedures but pass the state of the first procedure
by reference to the second procedure so it can be modified by the latter.
 
<lang freebasic>' FB 1.05.0 Win64
 
Sub makeItem(sep As String, ByRef counter As Integer, text As String)
counter += 1
Print counter; sep; text
End Sub
 
Sub makeList(sep As String)
Dim a(0 To 2) As String = {"first", "second", "third"}
Dim counter As Integer = 0
While counter < 3
makeItem(sep, counter, a(counter))
Wend
End Sub
 
makeList ". "
Print
Print "Press any key to quit"
Sleep
</lang>
 
{{out}}
<pre>
1. first
2. second
3. third
</pre>
 
=={{header|Free Pascal}}==
<langsyntaxhighlight lang="pascal">// In Pascal, functions always _have_ to return _some_ value,
// but the the task doesn’t specify what to return.
// Hence makeList and makeItem became procedures.
Line 588 ⟶ 761:
makeItem;
makeItem;
end;</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
 
FreeBASIC does not currently support either nested procedures or lambda expressions.
The best we can do here is to create two separate procedures but pass the state of the first procedure
by reference to the second procedure so it can be modified by the latter.
 
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub makeItem(sep As String, ByRef counter As Integer, text As String)
counter += 1
Print counter; sep; text
End Sub
 
Sub makeList(sep As String)
Dim a(0 To 2) As String = {"first", "second", "third"}
Dim counter As Integer = 0
While counter < 3
makeItem(sep, counter, a(counter))
Wend
End Sub
 
makeList ". "
Print
Print "Press any key to quit"
Sleep
</syntaxhighlight>
 
{{out}}
<pre>
1. first
2. second
3. third
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Nested_function}}
 
'''Solution'''
 
[[File:Fōrmulæ - Nested function 01.png]]
 
[[File:Fōrmulæ - Nested function 02.png]]
 
[[File:Fōrmulæ - Nested function 03.png]]
 
=={{header|Go}}==
 
<langsyntaxhighlight lang="go">package main
import "fmt"
 
Line 609 ⟶ 828:
func main() {
fmt.Print(makeList(". "))
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Control.Monad.ST
import Data.STRef
 
Line 628 ⟶ 847:
 
main :: IO ()
main = putStr $ makeList ". "</langsyntaxhighlight>
 
 
Or, importing a little less heavy machinery:
<syntaxhighlight lang="haskell">makeList :: String -> String
makeList separator =
let makeItem = (<>) . (<> separator) . show
in unlines $ zipWith makeItem [1 ..] ["First", "Second", "Third"]
 
main :: IO ()
main = putStrLn $ makeList ". "</syntaxhighlight>
 
or perhaps:
<syntaxhighlight lang="haskell">makeList :: String -> String
makeList separator =
let makeItem = unlines . zipWith ((<>) . (<> separator) . show) [1..]
in makeItem ["First", "Second", "Third"]
 
main :: IO ()
main = putStrLn $ makeList ". "</syntaxhighlight>
{{Out}}
<pre>1. First
2. Second
3. Third</pre>
 
=={{header|Io}}==
<langsyntaxhighlight Iolang="io">makeList := method(separator,
counter := 1
makeItem := method(item,
Line 640 ⟶ 882:
makeItem("first") .. makeItem("second") .. makeItem("third")
)
makeList(". ") print</langsyntaxhighlight>
 
=={{header|J}}==
Line 648 ⟶ 890:
That said, emulating a single level of nesting is relatively trivial and does not reflect the complexities necessary for more elaborate (and more difficult to understand) cases:
 
<langsyntaxhighlight Jlang="j">MakeList=: dyad define
sep_MakeList_=: x
cnt_MakeList_=: 0
Line 657 ⟶ 899:
cnt_MakeList_=: cnt_MakeList_+1
(":cnt_MakeList_),sep_MakeList_,y,LF
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> '. ' MakeList 'first';'second';'third'
1. first
2. second
3. third
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
Line 672 ⟶ 914:
Since version 8, Java has limited support for nested functions. All variables from the outer function that are accessed by the inner function have to be _effectively final_. This means that the counter cannot be a simple <tt>int</tt> variable; the closest way to emulate it is the <tt>AtomicInteger</tt> class.
 
<langsyntaxhighlight lang="java">import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
 
Line 688 ⟶ 930:
System.out.println(makeList(". "));
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
 
<langsyntaxhighlight lang="javascript">function makeList(separator) {
var counter = 1;
 
Line 702 ⟶ 944:
}
 
console.log(makeList(". "));</langsyntaxhighlight>
 
=={{header|jq}}==
 
<langsyntaxhighlight lang="jq">def makeList(separator):
# input: {text: _, counter: _}
def makeItem(item):
Line 717 ⟶ 959:
;
makeList(". ")</langsyntaxhighlight>
 
With the above in a file, say program.jq, the invocation:
Line 730 ⟶ 972:
=={{header|Jsish}}==
From Javascript entry.
<langsyntaxhighlight lang="javascript">/* Nested function, in Jsish */
function makeList(separator) {
var counter = 1;
Line 750 ⟶ 992:
 
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 759 ⟶ 1,001:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function makelist(sep::String)
cnt = 1
 
Line 771 ⟶ 1,013:
end
 
print(makelist(". "))</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun makeList(sep: String): String {
Line 787 ⟶ 1,029:
fun main(args: Array<String>) {
print(makeList(". "))
}</langsyntaxhighlight>
 
{{out}}
Line 795 ⟶ 1,037:
3. third
</pre>
 
=={{header|Lambdatalk}}==
Lambdatalk has neither closures nor states but we can do that, thanks to mutability of arrays behaving as "sandbox" of mutability.
<syntaxhighlight lang="scheme">
{def makeList
 
{def makeItem
{lambda {:s :a :i}
{div}{A.first {A.set! 0 {+ {A.first :a} 1} :a}}:s :i}}
 
{lambda {:s}
{S.map {{lambda {:s :a :i} {makeItem :s :a :i}}
:s {A.new 0}}
first second third
}}}
-> makeList
 
{makeList .}
->
1. first
2. second
3. third
</syntaxhighlight>
 
=={{header|Lua}}==
 
<langsyntaxhighlight lang="lua">function makeList (separator)
local counter = 0
local function makeItem(item)
Line 807 ⟶ 1,072:
end
print(makeList(". "))</langsyntaxhighlight>
{{out}}
<pre>1. first
Line 816 ⟶ 1,081:
In M2000 functions may have functions, modules, subs, but these are black boxes. We can define globals for temporary use. Subs can use anything from module/function where we call them. First example use Subs inside a module, when call Make_list two local variables, Separator$ and Counter allocated in same space as module's. So when we call Make_item() these variables are visible. At the exit of sub Make_list local variables destroyed. In second example Letter$ pop a string from stack of values (or an error raised if no string found).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Make_List(". ")
Line 858 ⟶ 1,123:
 
Make_List1 ". "
 
</lang>
Module Make_List (Separator$) {
Def Counter as Integer
// Need New before Item_Name$, because the scope is the module scope
// the scope defined from the calling method.
// by default a function has a new namespace.
Function Make_Item(New Item_Name$){
Counter++
Print Str$(Counter,"")+Separator$+Item_Name$
}
// Call Local place the module scope to function
// function called like a module
Call Local Make_Item("First")
Call Local Make_Item("Second")
Call Local Make_Item("Third")
Print "Counter=";Counter // 3
}
 
Make_List ". "
 
Module Make_List (Separator$) {
Def Counter
// using Module not Function.
Module Make_Item(New Item_Name$){
Counter++
Print Str$(Counter,"")+Separator$+Item_Name$
}
Call Local Make_Item,"First"
Call Local Make_Item,"Second"
Call Local Make_Item,"Third"
Print "Counter=";Counter // 3
}
 
Make_List ". "
 
 
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
makelist:=proc()
local makeitem,i;
Line 882 ⟶ 1,183:
end proc;
 
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">makeList[sep_String]:=Block[
{counter=0, makeItem},
makeItem[item_String]:=ToString[++counter]<>sep<>item;
makeItem /@ {"first", "second", "third"}
]
Scan[Print, makeList[". "]]</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
Note the <code>@</code> sigil is the key to altering <code>counter</code> in the outer scope.
<langsyntaxhighlight lang="min">(
:separator
1 :counter
Line 906 ⟶ 1,207:
) :make-list
 
". " make-list print</langsyntaxhighlight>
 
=={{header|MiniScript}}==
Subfunctions can directly read variables in the enclosing scope, but to assign to those variables, they must explicitly use the ''outer'' specifier (added in MiniScript version 1.5). This is similar to how global variables are accessed via ''globals''.
<langsyntaxhighlight MiniScriptlang="miniscript">makeList = function(sep)
counter = 0
makeItem = function(item)
Line 919 ⟶ 1,220:
end function
print makeList(". ")</langsyntaxhighlight>
Output:
<pre>["1. first", "2. second", "3. third"]</pre>
Line 925 ⟶ 1,226:
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def makeList(separator)
counter = 1
Line 937 ⟶ 1,238:
end
 
println makeList(". ")</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc makeList(separator: string): string =
var counter = 1
Line 946 ⟶ 1,247:
result = $counter & separator & item & "\n"
inc counter
return
makeItem("first") & makeItem("second") & makeItem("third")
 
echo $makeList(". ")</langsyntaxhighlight>
{{out}}
<pre>
Line 960 ⟶ 1,260:
=={{header|Objective-C}}==
 
<langsyntaxhighlight lang="objc">NSString *makeList(NSString *separator) {
__block int counter = 1;
Line 973 ⟶ 1,273:
NSLog(@"%@", makeList(@". "));
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let make_list separator =
let counter = ref 1 in
 
Line 989 ⟶ 1,289:
 
let () =
print_string (make_list ". ")</langsyntaxhighlight>
Interestingly, on my computer it prints the numbers in reverse order, probably because the order of evaluation of arguments (and thus order of access of the counter) is undetermined:
{{out}}
Line 1,003 ⟶ 1,303:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">sub makeList {
my $separator = shift;
my $counter = 1;
Line 1,012 ⟶ 1,312:
}
 
print makeList(". ");</langsyntaxhighlight>
 
=={{header|Perl 6}}==
 
<lang perl6>sub make-List ($separator = ') '){
my $count = 1;
 
sub make-Item ($item) { "{$count++}$separator$item" }
 
join "\n", <first second third>».&make-Item;
}
 
put make-List('. ');</lang>
{{out}}
<pre>1. first
2. second
3. third</pre>
 
=={{header|Phix}}==
There is only partial support for nested functions in Phix. Some prior work (over a single afternoon) has been left
{{improve|Phix|The Phix compiler needs enhancing to fully support nested functions.}}
unfinished, anyone interested can see it at [[Nested_function/Phix]], but it was just enough to open the door for
 
the two following reasonably acceptable work-arounds.<br>
Prior to this task, Phix had no support whatsoever for nested functions.<br>
Note that in both the following you cannot reference any local variables or parameters of the containing function,
Instead I have taken the first baby steps and documented them.<br>
but must pass in everything you need explicitly, and anything you need to update must be a reference type, which
If your distribution does not include the following demo, you need a later version (not yet uploaded at the
is only dictionaries and class instances, not integers, atoms, sequences, strings, or any user-defined types, as
time of writing). The source of that demo contains far more detailed information, and any updates.<br>
they are all effectively read-only. Referring to identifiers in the containing/outer function issues proper errors
 
in 1.0.0 and later, prior to that it simply won't work as hoped for.
Yes, this is pig-ugly, and incomplete. But it is a good start for anyone that needs nested functions, and
=== using a dictionary ===
shows what can be done in just a few (less than six) hours.
<syntaxhighlight lang="phix">function MakeList(string sep=". ")
 
function MakeItem(integer env, string sep)
NB as it stands, the compiler front-end "thinks" that l_counter and sep live in the same place. They are
integer counter = getd("counter",env)+1
properly separate in the runtime/VM, but the front-end will happily emit nonsense code if you let it.
setd("counter",counter,env)
<lang Phix>--
return sprintf("%d%s%s",{counter,sep,{"first","second","third"}[counter]})
-- demo\rosetta\Nested_function.exw
-- ================================
--
#ilASM{ jmp :fin
--
-- This is, of course, something the compiler should end up doing automatically,
-- and this assembly, or something similar, should be hidden away in builtins/VM.
--
:%opGetnlv -- [edi] := [esi] from frame edx
-- nb no reference counting (would be rqd)
[32]
sub esi,ebp -- --> frame offset
@@:
mov ecx,[ebp+20] -- ebp_prev
cmp [ecx+8],edx -- rtn
jne @b
mov eax,[esi+ecx]
mov [edi],eax
[64]
sub rsi,rbp -- --> frame offset
@@:
mov rcx,[rbp+40] -- rbp_prev
cmp [rcx+16],rdx -- rtn
jne @b
mov rax,[rsi+rcx]
mov [rdi],rax
[]
ret
 
:%opSetnlv -- [edi] in frame edx := [esi] (zeroed)
[32]
sub edi,ebp -- --> frame offset
@@:
mov ecx,[ebp+20] -- ebp_prev
cmp [ecx+8],edx -- rtn
jne @b
mov eax,[esi]
mov [edi+ecx],eax
-- mov [esi],ebx -- zero src
[64]
sub rdi,rbp -- --> frame offset
@@:
mov rcx,[rbp+40] -- rbp_prev
cmp [rcx+16],rdx -- rtn
jne @b
mov eax,[rsi]
mov [rdi+rcx],rax
-- mov [rsi],rbx -- zero src
[]
ret
::fin
}
 
function MakeList(string sep=". ")
integer counter = 0
function MakeItem()
-- -- what we'd really like to see:
-- counter += 1
-- return sprintf("%d%s%s",{counter,sep,{"first","second","third"}[counter]})
-- bar these locals, some idea of what the compiler should be doing:
integer l_counter
string l_sep
#ilASM{
[32]
mov edx,routine_id(MakeList)
lea esi,[counter]
lea edi,[l_counter]
call :%opGetnlv
lea esi,[sep]
lea edi,[l_sep]
call :%opGetnlv
[64]
mov rdx,routine_id(MakeList)
lea rsi,[counter]
lea rdi,[l_counter]
call :%opGetnlv
lea rsi,[sep]
lea rdi,[l_sep]
call :%opGetnlv
[]
}
l_counter += 1
#ilASM{
[32]
mov edx,routine_id(MakeList)
lea esi,[l_counter]
lea edi,[counter]
call :%opSetnlv
[64]
mov rdx,routine_id(MakeList)
lea rsi,[l_counter]
lea rdi,[counter]
call :%opSetnlv
[]
}
string res = sprintf("%d%s%s",{l_counter,l_sep,{"first","second","third"}[l_counter]})
#ilASM{
[32]
mov [l_sep],ebx -- (in lieu of proper refcounting)
[64]
mov [l_sep],rbx -- (in lieu of proper refcounting)
[]
}
return res
end function
integer counter = new_dict({{"counter",0}})
sequence res = {}
for i=1 to 3 do
res = append(res,MakeItem(counter,sep))
end for
return res
end function
 
?MakeList()</langsyntaxhighlight>
{{out}}
<pre>
{"1. first","2. second","3. third"}
</pre>
=== using a class ===
{{libheader|Phix/Class}}
Same output. I trust it is obvious that if you passed in c.count, you would not be able to update it.
Again note how MakeList's sep ''must'' be explicitly re-passed to MakeItem.<br>
Also note that the counter class ''cannot'' be made private to MakeList, however as a non-global it would automatically be private to a single source code file.
<syntaxhighlight lang="phix">class counter
public integer count
end class
function MakeList(string sep=". ")
function MakeItem(counter c, string sep)
c.count += 1
return sprintf("%d%s%s",{c.count,sep,{"first","second","third"}[c.count]})
end function
counter c = new()
sequence res = {}
for i=1 to 3 do
res = append(res,MakeItem(c,sep))
end for
return res
end function
?MakeList()</syntaxhighlight>
 
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<langsyntaxhighlight lang="php"><?
function makeList($separator) {
$counter = 1;
Line 1,176 ⟶ 1,380:
 
echo makeList(". ");
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de makeList (Sep)
(let (Cnt 0 makeItem '((Str) (prinl (inc 'Cnt) Sep Str)))
(makeItem "first")
Line 1,185 ⟶ 1,389:
(makeItem "third") ) )
 
(makeList ". ")</langsyntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|3+}}
<langsyntaxhighlight lang="python">def makeList(separator):
counter = 1
 
Line 1,200 ⟶ 1,404:
return makeItem("first") + makeItem("second") + makeItem("third")
 
print(makeList(". "))</langsyntaxhighlight>
=={{header|R}}==
This also shows that cat's sep argument is not the same as MakeList's.
<syntaxhighlight lang="rsplus">MakeList <- function(sep)
{
counter <- 0
MakeItem <- function() paste0(counter <<- counter + 1, sep, c("first", "second", "third")[counter])
cat(replicate(3, MakeItem()), sep = "\n")
}
MakeList(". ")</syntaxhighlight>
{{out}}
<pre>1. first
2. second
3. third</pre>
 
=={{header|Racket}}==
See also [[#Scheme]]; this demonstrates <code>map</code> a higher order function and <code>begin0</code> a form which saves us having to explicitly remember the result.
 
<langsyntaxhighlight lang="racket">#lang racket
 
(define (make-list separator)
Line 1,217 ⟶ 1,434:
(apply string-append (map make-item '(first second third))))
(display (make-list ". "))</langsyntaxhighlight>
 
{{out}}
<pre>1. first
2. second
3. third</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" line>sub make-List ($separator = ') '){
my $count = 1;
 
sub make-Item ($item) { "{$count++}$separator$item" }
 
join "\n", <first second third>».&make-Item;
}
 
put make-List('. ');</syntaxhighlight>
{{out}}
<pre>1. first
Line 1,227 ⟶ 1,461:
This REXX version is modeled after the '''FreeBASIC''' example &nbsp; (and it has the
same limitations).
<langsyntaxhighlight lang="rexx">/*REXX program showsdemonstrates that functions can be nested (an outer and inner function). */
ctr=0 0 /*initialize the CTR REXX variable.*/
call makeListMakeList '. ' /*invoke MakeList with the separator.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
makeItemMakeItem: parse arg sep,text; ctr= ctr +1 1 /*bump the counter variable. */
say ctr || sep || word(string$, ctr) /*display three thingys to the───► terminal. */
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
makeListMakeList: parse arg sep; string$= 'first second third' /*getobtain argumentsan argument; define a string.*/
do while ctr<3 /*keep truckin' until finished. */
call makeItemMakeItem sep, string $ /*invoke the makeItem MakeItem function. */
end /*while*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
'''output'''
<pre>
1. first
Line 1,249 ⟶ 1,483:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Nested function
 
Line 1,263 ⟶ 1,497:
makeitem(sep, counter, a[counter])
end
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,270 ⟶ 1,504:
3. third
</pre>
 
=={{header|RPL}}==
===Fully compliant===
The outer function creates the inner function, then deletes it at its last execution step.
The <code>\n</code> substring must be replaced by a <code>Newline</code> character when typing the code.
≪ + OVER →STR SWAP + ROT SWAP + SWAP 1 + ≫ ''''MakeItem'''' STO
"" 1
3 PICK "first\n" '''MakeItem''' 3 PICK "second\n" '''MakeItem''' 3 PICK "third\n" '''MakeItem'''
DROP SWAP DROP
''''MakeItem'''' PURGE
‘'''MakeList'''’ STO
 
". " '''MakeList'''
{{out}}
<pre>
1: "1. first
2. second
3. third"
</pre>
===Unnamed nested functions===
It is more idiomatic in RPL to use unnamed nested functions, which allows the use of local variables and then increases code readability.
≪ "" 1
1 3 '''FOR''' j
3 PICK { "first\n" "second\n" "third\n" } j GET
→ sep item ≪ DUP →STR sep + item + ROT SWAP + SWAP 1 + ≫
'''NEXT'''
DROP SWAP DROP
 
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">def makeList(separator)
counter = 1
 
Line 1,285 ⟶ 1,549:
end
 
print makeList(". ")</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">fn make_list(sep: &str) -> String {
let mut counter = 0;
let mut make_item = |label| {
Line 1,304 ⟶ 1,568:
fn main() {
println!("{}", make_list(". "))
}</langsyntaxhighlight>
 
{{out}}
Line 1,314 ⟶ 1,578:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">
<lang Scala>
def main(args: Array[String]) {
val sep: String=". "
Line 1,326 ⟶ 1,590:
go("third")
}
</langsyntaxhighlight>
 
{{out}}
Line 1,337 ⟶ 1,601:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">(define (make-list separator)
(define counter 1)
Line 1,347 ⟶ 1,611:
(string-append (make-item "first") (make-item "second") (make-item "third")))
 
(display (make-list ". "))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func string: makeList (in string: separator) is func
Line 1,373 ⟶ 1,637:
begin
write(makeList(". "));
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,383 ⟶ 1,647:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func make_list(separator = ') ') {
 
var count = 1
Line 1,393 ⟶ 1,657:
}
 
say make_list('. ')</langsyntaxhighlight>
{{out}}
<pre>
Line 1,402 ⟶ 1,666:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">COMMENT CLASS SIMSET IS SIMULA'S STANDARD LINKED LIST DATA TYPE
CLASS HEAD IS THE LIST ITSELF
CLASS LINK IS THE ELEMENT OF A LIST
Line 1,459 ⟶ 1,723:
 
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,469 ⟶ 1,733:
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">fun make_list separator =
let
val counter = ref 1;
Line 1,483 ⟶ 1,747:
end;
 
print (make_list ". ")</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
f = { |separator|
var count = 0;
Line 1,498 ⟶ 1,762:
 
f.(".")
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func makeList(_ separator: String) -> String {
var counter = 1
Line 1,514 ⟶ 1,778:
}
 
print(makeList(". "))</langsyntaxhighlight>
 
=={{header|Tcl}}==
The code below satisfies the specification (inspired by the Swift example). The inner function MakeItem (which gains read/write access to its caller's variables via upvar) is defined, called, and then discarded by renaming to {}. suchenwi
<langsyntaxhighlight Tcllang="tcl">#!/usr/bin/env tclsh
 
proc MakeList separator {
Line 1,533 ⟶ 1,797:
}
puts [MakeList ". "]
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Option Explicit
 
Private Const Sep As String = ". "
Private Counter As Integer
Sub Main()
Dim L As Variant
Counter = 0
L = MakeList(Array("first", "second", "third"))
Debug.Print L
End Sub
Function MakeList(Datas) As Variant
Dim i As Integer
For i = LBound(Datas) To UBound(Datas)
MakeList = MakeList & MakeItem(Datas(i))
Next i
End Function
Function MakeItem(Item As Variant) As Variant
Counter = Counter + 1
MakeItem = Counter & Sep & Item & vbCrLf
End Function</syntaxhighlight>
 
{{out}}
<pre>
1. first
2. second
3. third
</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var makeList = Fn.new { |sep|
var counter = 0
var makeItem = Fn.new { |name|
counter = counter + 1
return "%(counter)%(sep)%(name)"
}
var items = []
for (name in ["first", "second", "third"]) {
items.add(makeItem.call(name))
}
System.print(items.join("\n"))
}
 
makeList.call(". ")</syntaxhighlight>
 
{{out}}
<pre>
1. first
2. second
3. third
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">proc MakeList(Separator);
char Separator;
int Counter;
 
proc MakeItem;
int Ordinals;
[IntOut(0, Counter);
Text(0, Separator);
Ordinals:= [0, "first", "second", "third"];
Text(0, Ordinals(Counter));
CrLf(0);
];
 
for Counter:= 1 to 3 do MakeItem; \MakeList procedure
 
MakeList(". ") \main procedure</syntaxhighlight>
 
{{out}}
<pre>
1. first
2. second
3. third
</pre>
 
=={{header|zkl}}==
zkl functions don't have direct access to another functions scope, they are not nested. If a function is defined in another function, the compiler moves it out and hands you a reference to the function. So, you are unable to modify variables in the enclosing scope unless you are given a container which can be modified. Partial application can be used to bind [copies] of scope information to a function, that information is fixed at the point of application and becomes strictly local to the binding function (ie changes do not propagate). A Ref[erence] is a container that holds an object so it can be modified by other entities.
<langsyntaxhighlight lang="zkl">fcn makeList(separator){
counter:=Ref(1); // a container holding a one. A reference.
// 'wrap is partial application, in this case binding counter and separator
Line 1,544 ⟶ 1,885:
}
print(makeList(". "));</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits