Nested function: Difference between revisions
Content deleted Content added
Added Wren |
Added PL/M |
||
(46 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 217 ⟶ 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 255 ⟶ 381:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 264 ⟶ 390:
=={{header|C sharp|C#}}==
<
{
int counter = 1;
Line 273 ⟶ 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 283 ⟶ 409:
//using string interpolation
string MakeItem(string item) => $"{counter++}{separator}{item}\n";
}</
=={{header|C++}}==
{{works with|C++11}}
<
#include <string>
#include <vector>
Line 302 ⟶ 428:
for (auto item : makeList(". "))
std::cout << item << "\n";
}</
=={{header|Clojure}}==
<
(let [x (atom 0)]
(letfn [(make-item [item] (swap! x inc) (println (format "%s%s%s" @x separator item)))]
Line 313 ⟶ 439:
(make-item "third"))))
(make-list ". ")</
{{out}}
Line 324 ⟶ 450:
=={{header|Common Lisp}}==
<
(let ((counter 0))
(flet ((make-item (item)
Line 333 ⟶ 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 353 ⟶ 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 366 ⟶ 564:
var counter := 1;
var makeItem := (item){ var retVal := counter.toPrintable() + separator + item +
^ makeItem("first") + makeItem("second") + makeItem("third")
Line 374 ⟶ 572:
{
console.printLine(MakeList(". "))
}</
{{out}}
<pre>
Line 384 ⟶ 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 398 ⟶ 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 412 ⟶ 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 424 ⟶ 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 439 ⟶ 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 471 ⟶ 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 480 ⟶ 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 502 ⟶ 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.
Line 508 ⟶ 724:
=={{header|Free Pascal}}==
<
// but the the task doesn’t specify what to return.
// Hence makeList and makeItem became procedures.
Line 545 ⟶ 761:
makeItem;
makeItem;
end;</
=={{header|FreeBASIC}}==
Line 553 ⟶ 769:
by reference to the second procedure so it can be modified by the latter.
<
Sub makeItem(sep As String, ByRef counter As Integer, text As String)
Line 572 ⟶ 788:
Print "Press any key to quit"
Sleep
</syntaxhighlight>
{{out}}
Line 583 ⟶ 799:
=={{header|Fōrmulæ}}==
'''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 608 ⟶ 828:
func main() {
fmt.Print(makeList(". "))
}</
=={{header|Haskell}}==
<
import Data.STRef
Line 627 ⟶ 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 639 ⟶ 882:
makeItem("first") .. makeItem("second") .. makeItem("third")
)
makeList(". ") print</
=={{header|J}}==
Line 647 ⟶ 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 656 ⟶ 899:
cnt_MakeList_=: cnt_MakeList_+1
(":cnt_MakeList_),sep_MakeList_,y,LF
)</
Example use:
<
1. first
2. second
3. third
</syntaxhighlight>
=={{header|Java}}==
Line 671 ⟶ 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 687 ⟶ 930:
System.out.println(makeList(". "));
}
}</
=={{header|JavaScript}}==
<
var counter = 1;
Line 701 ⟶ 944:
}
console.log(makeList(". "));</
=={{header|jq}}==
<
# input: {text: _, counter: _}
def makeItem(item):
Line 716 ⟶ 959:
;
makeList(". ")</
With the above in a file, say program.jq, the invocation:
Line 729 ⟶ 972:
=={{header|Jsish}}==
From Javascript entry.
<
function makeList(separator) {
var counter = 1;
Line 749 ⟶ 992:
=!EXPECTEND!=
*/</
{{out}}
Line 758 ⟶ 1,001:
{{works with|Julia|0.6}}
<
cnt = 1
Line 770 ⟶ 1,013:
end
print(makelist(". "))</
=={{header|Kotlin}}==
<
fun makeList(sep: String): String {
Line 786 ⟶ 1,029:
fun main(args: Array<String>) {
print(makeList(". "))
}</
{{out}}
Line 794 ⟶ 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 806 ⟶ 1,072:
end
print(makeList(". "))</
{{out}}
<pre>1. first
Line 815 ⟶ 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 857 ⟶ 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 881 ⟶ 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 905 ⟶ 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 918 ⟶ 1,220:
end function
print makeList(". ")</
Output:
<pre>["1. first", "2. second", "3. third"]</pre>
Line 924 ⟶ 1,226:
=={{header|Nanoquery}}==
{{trans|Python}}
<
counter = 1
Line 936 ⟶ 1,238:
end
println makeList(". ")</
=={{header|Nim}}==
<
var counter = 1
Line 945 ⟶ 1,247:
result = $counter & separator & item & "\n"
inc counter
makeItem("first") & makeItem("second") & makeItem("third")
echo $makeList(". ")</
{{out}}
<pre>
Line 959 ⟶ 1,260:
=={{header|Objective-C}}==
<
__block int counter = 1;
Line 972 ⟶ 1,273:
NSLog(@"%@", makeList(@". "));
return 0;
}</
=={{header|OCaml}}==
<
let counter = ref 1 in
Line 988 ⟶ 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 999 ⟶ 1,300:
=={{header|Pascal}}==
''See [[#Free Pascal|Free Pascal]]''
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
procedure MakeList(separator: string);
var counter := 1;
procedure MakeItem;
begin
Write(counter, separator);
case counter of
1: Writeln('first');
2: Writeln('second');
3: Writeln('third');
end;
counter += 1;
end;
begin
MakeItem;
MakeItem;
MakeItem;
end;
begin
MakeList('. ');
end.
</syntaxhighlight>
{{out}}
<pre>
1. first
2. second
3. third
</pre>
=={{header|Perl}}==
<
my $separator = shift;
my $counter = 1;
Line 1,011 ⟶ 1,343:
}
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,159 ⟶ 1,411:
echo makeList(". ");
?></
=={{header|PicoLisp}}==
<
(let (Cnt 0 makeItem '((Str) (prinl (inc 'Cnt) Sep Str)))
(makeItem "first")
Line 1,168 ⟶ 1,420:
(makeItem "third") ) )
(makeList ". ")</
=={{header|PL/M}}==
{{works with|8080 PL/M Compiler|... under CP/M (or an emulator)}}
In CP/M and by convention in PL/M, strings are terminated by $.<br/>
Note the original 8080 PL/M compiler treats lower case letters as spaces in the source, so the list is in upper case in this sample.
<syntaxhighlight lang="plm">
100H: /* USE A NESTED PROCEDURE TO CONSTRUCT A STRING, UPDATING VARIABLES IN */
/* THE CONTAINING PROCEDURE */
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;END;
/* CONSOLE OUTPUT ROUTINES */
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
/* CONCATENATES ITEM TO THE END OF STR. STR MUST BE LONG ENOUGH TO HOLD */
/* THE CONCATENATED VALUE */
CONCAT: PROCEDURE( STR, ITEM );
DECLARE ( STR, ITEM ) ADDRESS;
DECLARE STR$S BASED STR ( 0 )BYTE;
DECLARE ITEM$S BASED ITEM ( 0 )BYTE;
DECLARE ( STR$POS, ITEM$POS ) BYTE;
/* FIND THE CURRENT END OF STR */
STR$POS = 0;
DO WHILE STR$S( STR$POS ) <> '$';
STR$POS = STR$POS + 1;
END;
/* COPY ITEM TO THE END OF STR */
ITEM$POS = 0;
DO WHILE ITEM$S( ITEM$POS ) <> '$';
STR$S( STR$POS ) = ITEM$S( ITEM$POS );
ITEM$POS = ITEM$POS + 1;
STR$POS = STR$POS + 1;
END;
STR$S( STR$POS ) = '$';
END CONCAT ;
/* TASK */
/* RETURNS THE ADDRESS OF A STRING CONCATENATED FROM CALLS TO THE NESTED */
/* MAKE$ITEM PROCEDURE - THE RESULTANT STRING MUST NOT BE MORE */
/* THAN 64 CHARACTERS IN LENGTH */
MAKE$LIST: PROCEDURE( SEPARATOR )ADDRESS;
DECLARE SEPARATOR ADDRESS;
DECLARE LIST$VALUE ( 65 )BYTE;
DECLARE COUNTER BYTE;
/* RETURNS THE ADDRESS OF A LIST ITEM, THE LENGTH OF THE ITEM MUST'NT */
/* BE MORE THAN 32 CHARACTERS */
MAKE$ITEM: PROCEDURE( ITEM )ADDRESS;
DECLARE ITEM ADDRESS;
DECLARE LIST$ITEM ( 33 )BYTE;
COUNTER = COUNTER + 1;
LIST$ITEM( 0 ) = '0' + COUNTER;
LIST$ITEM( 1 ) = '$';
CALL CONCAT( .LIST$ITEM, SEPARATOR );
CALL CONCAT( .LIST$ITEM, ITEM );
CALL CONCAT( .LIST$ITEM, .( 0DH, 0AH, '$' ) );
RETURN .LIST$ITEM;
END MAKE$ITEM ;
COUNTER = 0;
LIST$VALUE( 0 ) = '$';
CALL CONCAT( .LISTVALUE, MAKE$ITEM( .'FIRST$' ) );
CALL CONCAT( .LISTVALUE, MAKE$ITEM( .'SECOND$' ) );
CALL CONCAT( .LISTVALUE, MAKE$ITEM( .'THIRD$' ) );
RETURN .LIST$VALUE;
END MAKE$LIST ;
CALL PR$STRING( MAKE$LIST( .'. $' ) );
EOF
</syntaxhighlight>
{{out}}
<pre>
1. FIRST
2. SECOND
3. THIRD
</pre>
=={{header|Python}}==
{{works with|Python|3+}}
<
counter = 1
Line 1,183 ⟶ 1,522:
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,200 ⟶ 1,552:
(apply string-append (map make-item '(first second third))))
(display (make-list ". "))</
{{out}}
Line 1,210 ⟶ 1,562:
(formerly Perl 6)
<syntaxhighlight lang="raku"
my $count = 1;
Line 1,218 ⟶ 1,570:
}
put make-List('. ');</
{{out}}
<pre>1. first
Line 1,227 ⟶ 1,579:
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,601:
=={{header|Ring}}==
<
# Project : Nested function
Line 1,263 ⟶ 1,615:
makeitem(sep, counter, a[counter])
end
</syntaxhighlight>
Output:
<pre>
Line 1,270 ⟶ 1,622:
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,667:
end
print makeList(". ")</
=={{header|Rust}}==
<
let mut counter = 0;
let mut make_item = |label| {
Line 1,304 ⟶ 1,686:
fn main() {
println!("{}", make_list(". "))
}</
{{out}}
Line 1,314 ⟶ 1,696:
=={{header|Scala}}==
<syntaxhighlight lang="scala">
def main(args: Array[String]) {
val sep: String=". "
Line 1,326 ⟶ 1,708:
go("third")
}
</
{{out}}
Line 1,337 ⟶ 1,719:
=={{header|Scheme}}==
<
(define counter 1)
Line 1,347 ⟶ 1,729:
(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,755:
begin
write(makeList(". "));
end func;</
{{out}}
Line 1,383 ⟶ 1,765:
=={{header|Sidef}}==
<
var count = 1
Line 1,393 ⟶ 1,775:
}
say make_list('. ')</
{{out}}
<pre>
Line 1,402 ⟶ 1,784:
=={{header|Simula}}==
<
CLASS HEAD IS THE LIST ITSELF
CLASS LINK IS THE ELEMENT OF A LIST
Line 1,459 ⟶ 1,841:
END.
</syntaxhighlight>
{{out}}
<pre>
Line 1,469 ⟶ 1,851:
=={{header|Standard ML}}==
<
let
val counter = ref 1;
Line 1,483 ⟶ 1,865:
end;
print (make_list ". ")</
=={{header|SuperCollider}}==
<syntaxhighlight lang="supercollider">(
f = { |separator|
var count = 0;
Line 1,498 ⟶ 1,880:
f.(".")
</syntaxhighlight>
=={{header|Swift}}==
<
var counter = 1
Line 1,514 ⟶ 1,896:
}
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,915:
}
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}}==
<
var counter = 0
var makeItem = Fn.new { |name|
Line 1,549 ⟶ 1,960:
}
makeList.call(". ")</
{{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}}
Line 1,560 ⟶ 1,996:
=={{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,567 ⟶ 2,003:
}
print(makeList(". "));</
{{out}}
<pre>
|