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.
;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:
:* [[wp:Nested function|Nested function]]
<br><br>
=={{header|11l}}==
{{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}}==
<
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;</
{{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}}==
<
BEGIN
INT counter := 0;
Line 66 ⟶ 149:
print( ( make list( ". " ) ) )
</syntaxhighlight>
=={{header|ALGOL W}}==
Algol W strings are fixed length which makes this slightly more complicated than the Algol 68 solution.
<
string(30) procedure makeList ( string(2) value separator ) ;
begin
Line 94 ⟶ 177:
end; % makeList %
write( makeList( ". " ) )
end.</
=={{header|AppleScript}}==
<
-- makeList :: String -> String
Line 115 ⟶ 198:
end makeList
on run
Line 123 ⟶ 206:
-- 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>
{{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:
<
on makeList(separator)
Line 167 ⟶ 253:
map(makeItem, ["first", "second", "third"]) as string
end makeList</
=={{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">
(* ****** ****** *)
//
Line 208 ⟶ 319:
(* ****** ****** *)
</syntaxhighlight>
=={{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">
#include<stdlib.h>
#include<stdio.h>
Line 256 ⟶ 381:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 264 ⟶ 389:
</pre>
=={{header|C
<syntaxhighlight lang="csharp">string MakeList(string separator)
{
int counter = 1;
Line 293 ⟶ 399:
}
Console.WriteLine(MakeList(". "));</
'''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.
<
{
int counter = 1;
Line 303 ⟶ 409:
//using string interpolation
string MakeItem(string item) => $"{counter++}{separator}{item}\n";
}</
=={{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}}==
<
(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 ". ")</
{{out}}
Line 325 ⟶ 450:
=={{header|Common Lisp}}==
<
(let ((counter 0))
(flet ((make-item (item)
Line 334 ⟶ 459:
(make-item "third")))))
(format t (my-make-list ". "))</
''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}}==
<
int counter = 1;
Line 354 ⟶ 518:
import std.stdio : writeln;
writeln(makeList(". "));
}</
{{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
<
MakeList(separator)
Line 367 ⟶ 564:
var counter := 1;
var makeItem := (item){ var retVal := counter.
^ makeItem("first") + makeItem("second") + makeItem("third")
Line 375 ⟶ 572:
{
console.printLine(MakeList(". "))
}</
{{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:
<
def makeList(separator) do
counter = 1
Line 399 ⟶ 596:
end
IO.write Nested.makeList(". ")</
{{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.
<
IN: rosetta-code.nested-functions
Line 425 ⟶ 640:
;
". " make-list write</
=={{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:<
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</
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. <
CHARACTER*(*) TEXT !The supplied scratchpad.
INTEGER L !Its length.
Line 480 ⟶ 687:
CALL POOBAH(TEXT,L,". ")
WRITE (6,"(A)") TEXT(1:L)
END</
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.<
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</
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|Free Pascal}}==
<
// but the the task doesn’t specify what to return.
// Hence makeList and makeItem became procedures.
Line 588 ⟶ 761:
makeItem;
makeItem;
end;</
=={{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}}==
<
import "fmt"
Line 609 ⟶ 828:
func main() {
fmt.Print(makeList(". "))
}</
=={{header|Haskell}}==
<
import Data.STRef
Line 628 ⟶ 847:
main :: IO ()
main = putStr $ makeList ". "</
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}}==
<
counter := 1
makeItem := method(item,
Line 640 ⟶ 882:
makeItem("first") .. makeItem("second") .. makeItem("third")
)
makeList(". ") print</
=={{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:
<
sep_MakeList_=: x
cnt_MakeList_=: 0
Line 657 ⟶ 899:
cnt_MakeList_=: cnt_MakeList_+1
(":cnt_MakeList_),sep_MakeList_,y,LF
)</
Example use:
<
1. first
2. second
3. third
</syntaxhighlight>
=={{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.
<
import java.util.function.Function;
Line 688 ⟶ 930:
System.out.println(makeList(". "));
}
}</
=={{header|JavaScript}}==
<
var counter = 1;
Line 702 ⟶ 944:
}
console.log(makeList(". "));</
=={{header|jq}}==
<
# input: {text: _, counter: _}
def makeItem(item):
Line 717 ⟶ 959:
;
makeList(". ")</
With the above in a file, say program.jq, the invocation:
Line 730 ⟶ 972:
=={{header|Jsish}}==
From Javascript entry.
<
function makeList(separator) {
var counter = 1;
Line 750 ⟶ 992:
=!EXPECTEND!=
*/</
{{out}}
Line 759 ⟶ 1,001:
{{works with|Julia|0.6}}
<
cnt = 1
Line 771 ⟶ 1,013:
end
print(makelist(". "))</
=={{header|Kotlin}}==
<
fun makeList(sep: String): String {
Line 787 ⟶ 1,029:
fun main(args: Array<String>) {
print(makeList(". "))
}</
{{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}}==
<
local counter = 0
local function makeItem(item)
Line 807 ⟶ 1,072:
end
print(makeList(". "))</
{{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">
Module Checkit {
Make_List(". ")
Line 858 ⟶ 1,123:
Make_List1 ". "
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">
makelist:=proc()
local makeitem,i;
Line 882 ⟶ 1,183:
end proc;
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{counter=0, makeItem},
makeItem[item_String]:=ToString[++counter]<>sep<>item;
makeItem /@ {"first", "second", "third"}
]
Scan[Print, makeList[". "]]</
=={{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.
<
:separator
1 :counter
Line 906 ⟶ 1,207:
) :make-list
". " make-list print</
=={{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''.
<
counter = 0
makeItem = function(item)
Line 919 ⟶ 1,220:
end function
print makeList(". ")</
Output:
<pre>["1. first", "2. second", "3. third"]</pre>
Line 925 ⟶ 1,226:
=={{header|Nanoquery}}==
{{trans|Python}}
<
counter = 1
Line 937 ⟶ 1,238:
end
println makeList(". ")</
=={{header|Nim}}==
<
var counter = 1
Line 946 ⟶ 1,247:
result = $counter & separator & item & "\n"
inc counter
makeItem("first") & makeItem("second") & makeItem("third")
echo $makeList(". ")</
{{out}}
<pre>
Line 960 ⟶ 1,260:
=={{header|Objective-C}}==
<
__block int counter = 1;
Line 973 ⟶ 1,273:
NSLog(@"%@", makeList(@". "));
return 0;
}</
=={{header|OCaml}}==
<
let counter = ref 1 in
Line 989 ⟶ 1,289:
let () =
print_string (make_list ". ")</
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}}==
<
my $separator = shift;
my $counter = 1;
Line 1,012 ⟶ 1,312:
}
print makeList(". ");</
=={{header|Phix}}==
There is only partial support for nested functions in Phix. Some prior work (over a single afternoon) has been left
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>
Note that in both the following you cannot reference any local variables or parameters of the containing function,
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. 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.
=== using a dictionary ===
<syntaxhighlight lang="phix">function MakeList(string sep=". ")
function MakeItem(integer env, string sep)
integer counter = getd("counter",env)+1
setd("counter",counter,env)
return sprintf("%d%s%s",{counter,sep,{"first","second","third"}[counter]})
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()</
{{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+}}
<
function makeList($separator) {
$counter = 1;
Line 1,176 ⟶ 1,380:
echo makeList(". ");
?></
=={{header|PicoLisp}}==
<
(let (Cnt 0 makeItem '((Str) (prinl (inc 'Cnt) Sep Str)))
(makeItem "first")
Line 1,185 ⟶ 1,389:
(makeItem "third") ) )
(makeList ". ")</
=={{header|Python}}==
{{works with|Python|3+}}
<
counter = 1
Line 1,200 ⟶ 1,404:
return makeItem("first") + makeItem("second") + makeItem("third")
print(makeList(". "))</
=={{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.
<
(define (make-list separator)
Line 1,217 ⟶ 1,434:
(apply string-append (map make-item '(first second third))))
(display (make-list ". "))</
{{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 (and it has the
same limitations).
<
ctr=
call
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
say ctr || sep || word(
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
do while ctr<3
call
end /*while*/
return</
{{out|output|text= when using the default input:}}
<pre>
1. first
Line 1,249 ⟶ 1,483:
=={{header|Ring}}==
<
# Project : Nested function
Line 1,263 ⟶ 1,497:
makeitem(sep, counter, a[counter])
end
</syntaxhighlight>
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}}==
<
counter = 1
Line 1,285 ⟶ 1,549:
end
print makeList(". ")</
=={{header|Rust}}==
<
let mut counter = 0;
let mut make_item = |label| {
Line 1,304 ⟶ 1,568:
fn main() {
println!("{}", make_list(". "))
}</
{{out}}
Line 1,314 ⟶ 1,578:
=={{header|Scala}}==
<syntaxhighlight lang="scala">
def main(args: Array[String]) {
val sep: String=". "
Line 1,326 ⟶ 1,590:
go("third")
}
</
{{out}}
Line 1,337 ⟶ 1,601:
=={{header|Scheme}}==
<
(define counter 1)
Line 1,347 ⟶ 1,611:
(string-append (make-item "first") (make-item "second") (make-item "third")))
(display (make-list ". "))</
=={{header|Seed7}}==
<
const func string: makeList (in string: separator) is func
Line 1,373 ⟶ 1,637:
begin
write(makeList(". "));
end func;</
{{out}}
Line 1,383 ⟶ 1,647:
=={{header|Sidef}}==
<
var count = 1
Line 1,393 ⟶ 1,657:
}
say make_list('. ')</
{{out}}
<pre>
Line 1,402 ⟶ 1,666:
=={{header|Simula}}==
<
CLASS HEAD IS THE LIST ITSELF
CLASS LINK IS THE ELEMENT OF A LIST
Line 1,459 ⟶ 1,723:
END.
</syntaxhighlight>
{{out}}
<pre>
Line 1,469 ⟶ 1,733:
=={{header|Standard ML}}==
<
let
val counter = ref 1;
Line 1,483 ⟶ 1,747:
end;
print (make_list ". ")</
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">(
f = { |separator|
var count = 0;
Line 1,498 ⟶ 1,762:
f.(".")
</syntaxhighlight>
=={{header|Swift}}==
<
var counter = 1
Line 1,514 ⟶ 1,778:
}
print(makeList(". "))</
=={{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
<
proc MakeList separator {
Line 1,533 ⟶ 1,797:
}
puts [MakeList ". "]
</syntaxhighlight>
=={{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.
<
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(". "));</
{{out}}
<pre>
|