Nested function: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎using a class: added phix/class)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(40 intermediate revisions by 21 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 --------------------
 
-- makeList :: String -> String
Line 150 ⟶ 233:
return lst
end tell
end map</langsyntaxhighlight>
{{Out}}
<pre>1. first
Line 159 ⟶ 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 170 ⟶ 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 211 ⟶ 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 220 ⟶ 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 258 ⟶ 381:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 267 ⟶ 390:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">string MakeList(string separator)
{
int counter = 1;
Line 276 ⟶ 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 286 ⟶ 409:
//using string interpolation
string MakeItem(string item) => $"{counter++}{separator}{item}\n";
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <vector>
Line 305 ⟶ 428:
for (auto item : makeList(". "))
std::cout << item << "\n";
}</langsyntaxhighlight>
 
=={{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 316 ⟶ 439:
(make-item "third"))))
 
(make-list ". ")</langsyntaxhighlight>
 
{{out}}
Line 327 ⟶ 450:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun my-make-list (separator)
(let ((counter 0))
(flet ((make-item (item)
Line 336 ⟶ 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 356 ⟶ 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 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
MakeList(separator)
Line 369 ⟶ 564:
var counter := 1;
var makeItem := (item){ var retVal := counter.toPrintable() + separator + item + (forward newLine)newLineConstant; counter += 1; ^ retVal };
^ makeItem("first") + makeItem("second") + makeItem("third")
Line 377 ⟶ 572:
{
console.printLine(MakeList(". "))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 387 ⟶ 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 401 ⟶ 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 415 ⟶ 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 427 ⟶ 640:
;
". " make-list write</langsyntaxhighlight>
 
=={{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 442 ⟶ 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 474 ⟶ 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 483 ⟶ 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 505 ⟶ 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.
 
Line 511 ⟶ 724:
 
=={{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 548 ⟶ 761:
makeItem;
makeItem;
end;</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Line 556 ⟶ 769:
by reference to the second procedure so it can be modified by the latter.
 
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Sub makeItem(sep As String, ByRef counter As Integer, text As String)
Line 575 ⟶ 788:
Print "Press any key to quit"
Sleep
</syntaxhighlight>
</lang>
 
{{out}}
Line 586 ⟶ 799:
=={{header|Fōrmulæ}}==
 
In [http{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Nested_function this] page you can see the solution of this task.}}
 
'''Solution'''
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.
 
[[File:Fōrmulæ - Nested function 01.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
[[File:Fōrmulæ - Nested function 02.png]]
 
[[File:Fōrmulæ - Nested function 03.png]]
 
=={{header|Go}}==
 
<langsyntaxhighlight lang="go">package main
import "fmt"
 
Line 611 ⟶ 828:
func main() {
fmt.Print(makeList(". "))
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Control.Monad.ST
import Data.STRef
 
Line 630 ⟶ 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 642 ⟶ 882:
makeItem("first") .. makeItem("second") .. makeItem("third")
)
makeList(". ") print</langsyntaxhighlight>
 
=={{header|J}}==
Line 650 ⟶ 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 659 ⟶ 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 674 ⟶ 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 690 ⟶ 930:
System.out.println(makeList(". "));
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
 
<langsyntaxhighlight lang="javascript">function makeList(separator) {
var counter = 1;
 
Line 704 ⟶ 944:
}
 
console.log(makeList(". "));</langsyntaxhighlight>
 
=={{header|jq}}==
 
<langsyntaxhighlight lang="jq">def makeList(separator):
# input: {text: _, counter: _}
def makeItem(item):
Line 719 ⟶ 959:
;
makeList(". ")</langsyntaxhighlight>
 
With the above in a file, say program.jq, the invocation:
Line 732 ⟶ 972:
=={{header|Jsish}}==
From Javascript entry.
<langsyntaxhighlight lang="javascript">/* Nested function, in Jsish */
function makeList(separator) {
var counter = 1;
Line 752 ⟶ 992:
 
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 761 ⟶ 1,001:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function makelist(sep::String)
cnt = 1
 
Line 773 ⟶ 1,013:
end
 
print(makelist(". "))</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun makeList(sep: String): String {
Line 789 ⟶ 1,029:
fun main(args: Array<String>) {
print(makeList(". "))
}</langsyntaxhighlight>
 
{{out}}
Line 797 ⟶ 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 809 ⟶ 1,072:
end
print(makeList(". "))</langsyntaxhighlight>
{{out}}
<pre>1. first
Line 818 ⟶ 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 860 ⟶ 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 884 ⟶ 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 908 ⟶ 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 921 ⟶ 1,220:
end function
print makeList(". ")</langsyntaxhighlight>
Output:
<pre>["1. first", "2. second", "3. third"]</pre>
Line 927 ⟶ 1,226:
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def makeList(separator)
counter = 1
Line 939 ⟶ 1,238:
end
 
println makeList(". ")</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc makeList(separator: string): string =
var counter = 1
Line 948 ⟶ 1,247:
result = $counter & separator & item & "\n"
inc counter
return
makeItem("first") & makeItem("second") & makeItem("third")
 
echo $makeList(". ")</langsyntaxhighlight>
{{out}}
<pre>
Line 962 ⟶ 1,260:
=={{header|Objective-C}}==
 
<langsyntaxhighlight lang="objc">NSString *makeList(NSString *separator) {
__block int counter = 1;
Line 975 ⟶ 1,273:
NSLog(@"%@", makeList(@". "));
return 0;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let make_list separator =
let counter = ref 1 in
 
Line 991 ⟶ 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,005 ⟶ 1,303:
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">sub makeList {
my $separator = shift;
my $counter = 1;
Line 1,014 ⟶ 1,312:
}
 
print makeList(". ");</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 1,023 ⟶ 1,321:
but must pass in everything you need explicitly, and anything you need to update must be a reference type, which
is only dictionaries and class instances, not integers, atoms, sequences, strings, or any user-defined types, as
they are all effectively read-only. AlsoReferring noteto thatidentifiers in the compilercontaining/outer willfunction not (as yet) issue anyissues proper errors or
warningsin should1.0.0 youand breaklater, thatprior restriction,to insteadthat it simply won't work as hoped for.
=== using a dictionary ===
<langsyntaxhighlight Phixlang="phix">function MakeList(string sep=". ")
function MakeItem(integer env, string sep)
integer counter = getd("counter",env)+1
Line 1,040 ⟶ 1,338:
end function
?MakeList()</langsyntaxhighlight>
{{out}}
<pre>
Line 1,048 ⟶ 1,346:
{{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>
<lang Phix>class counter
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
Line 1,064 ⟶ 1,364:
end function
?MakeList()</langsyntaxhighlight>
 
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<langsyntaxhighlight lang="php"><?
function makeList($separator) {
$counter = 1;
Line 1,080 ⟶ 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,089 ⟶ 1,389:
(makeItem "third") ) )
 
(makeList ". ")</langsyntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|3+}}
<langsyntaxhighlight lang="python">def makeList(separator):
counter = 1
 
Line 1,104 ⟶ 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,121 ⟶ 1,434:
(apply string-append (map make-item '(first second third))))
(display (make-list ". "))</langsyntaxhighlight>
 
{{out}}
Line 1,131 ⟶ 1,444:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>sub make-List ($separator = ') '){
my $count = 1;
 
Line 1,139 ⟶ 1,452:
}
 
put make-List('. ');</langsyntaxhighlight>
{{out}}
<pre>1. first
Line 1,148 ⟶ 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,170 ⟶ 1,483:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Nested function
 
Line 1,184 ⟶ 1,497:
makeitem(sep, counter, a[counter])
end
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,191 ⟶ 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,206 ⟶ 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,225 ⟶ 1,568:
fn main() {
println!("{}", make_list(". "))
}</langsyntaxhighlight>
 
{{out}}
Line 1,235 ⟶ 1,578:
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">
<lang Scala>
def main(args: Array[String]) {
val sep: String=". "
Line 1,247 ⟶ 1,590:
go("third")
}
</langsyntaxhighlight>
 
{{out}}
Line 1,258 ⟶ 1,601:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">(define (make-list separator)
(define counter 1)
Line 1,268 ⟶ 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,294 ⟶ 1,637:
begin
write(makeList(". "));
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,304 ⟶ 1,647:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func make_list(separator = ') ') {
 
var count = 1
Line 1,314 ⟶ 1,657:
}
 
say make_list('. ')</langsyntaxhighlight>
{{out}}
<pre>
Line 1,323 ⟶ 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,380 ⟶ 1,723:
 
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,390 ⟶ 1,733:
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">fun make_list separator =
let
val counter = ref 1;
Line 1,404 ⟶ 1,747:
end;
 
print (make_list ". ")</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">(
<lang SuperCollider>(
f = { |separator|
var count = 0;
Line 1,419 ⟶ 1,762:
 
f.(".")
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func makeList(_ separator: String) -> String {
var counter = 1
Line 1,435 ⟶ 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,454 ⟶ 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}}==
<langsyntaxhighlight ecmascriptlang="wren">var makeList = Fn.new { |sep|
var counter = 0
var makeItem = Fn.new { |name|
Line 1,470 ⟶ 1,842:
}
 
makeList.call(". ")</langsyntaxhighlight>
 
{{out}}
Line 1,480 ⟶ 1,852:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">proc MakeList(Separator);
char Separator;
int Counter;
Line 1,495 ⟶ 1,867:
for Counter:= 1 to 3 do MakeItem; \MakeList procedure
 
MakeList(". ") \main procedure</langsyntaxhighlight>
 
{{out}}
Line 1,506 ⟶ 1,878:
=={{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,513 ⟶ 1,885:
}
print(makeList(". "));</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits