Loops/Foreach: Difference between revisions

Content added Content deleted
(add Zig example with TODO for next() method)
m (syntax highlighting fixup automation)
Line 26: Line 26:
{{trans|C#}}
{{trans|C#}}


<lang 11l>V things = [‘Apple’, ‘Banana’, ‘Coconut’]
<syntaxhighlight lang="11l">V things = [‘Apple’, ‘Banana’, ‘Coconut’]


L(thing) things
L(thing) things
print(thing)</lang>
print(thing)</syntaxhighlight>


=={{header|ACL2}}==
=={{header|ACL2}}==


<lang Lisp>(defun print-list (xs)
<syntaxhighlight lang="lisp">(defun print-list (xs)
(if (endp xs)
(if (endp xs)
nil
nil
(prog2$ (cw "~x0~%" (first xs))
(prog2$ (cw "~x0~%" (first xs))
(print-list (rest xs)))))</lang>
(print-list (rest xs)))))</syntaxhighlight>


<pre>
<pre>
Line 51: Line 51:
=={{header|Action!}}==
=={{header|Action!}}==
In Action! there is no for-each loop.
In Action! there is no for-each loop.
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
DEFINE PTR="CARD"
DEFINE PTR="CARD"
BYTE i
BYTE i
Line 67: Line 67:
PrintE(items(i))
PrintE(items(i))
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Foreach.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Foreach.png Screenshot from Atari 8-bit computer]
Line 87: Line 87:
=={{header|Ada}}==
=={{header|Ada}}==
===arrays===
===arrays===
<lang Ada>with Ada.Integer_Text_IO;
<syntaxhighlight lang="ada">with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;


Line 100: Line 100:
end loop;
end loop;


end For_Each;</lang>
end For_Each;</syntaxhighlight>


Alternative solution (Ada 2012):
Alternative solution (Ada 2012):


<lang Ada> for Item of A loop
<syntaxhighlight lang="ada"> for Item of A loop
Put( Item );
Put( Item );
end loop;</lang>
end loop;</syntaxhighlight>


===doubly linked lists===
===doubly linked lists===
{{works with|Ada 2005}}
{{works with|Ada 2005}}
<lang Ada>with Ada.Integer_Text_IO, Ada.Containers.Doubly_Linked_Lists;
<syntaxhighlight lang="ada">with Ada.Integer_Text_IO, Ada.Containers.Doubly_Linked_Lists;
use Ada.Integer_Text_IO, Ada.Containers;
use Ada.Integer_Text_IO, Ada.Containers;


Line 134: Line 134:
DL_List.Iterate (Print_Node'Access);
DL_List.Iterate (Print_Node'Access);
end Doubly_Linked_List;</lang>
end Doubly_Linked_List;</syntaxhighlight>
===vectors===
===vectors===
{{works with|Ada 2005}}
{{works with|Ada 2005}}
<lang Ada>with Ada.Integer_Text_IO, Ada.Containers.Vectors;
<syntaxhighlight lang="ada">with Ada.Integer_Text_IO, Ada.Containers.Vectors;
use Ada.Integer_Text_IO, Ada.Containers;
use Ada.Integer_Text_IO, Ada.Containers;


Line 161: Line 161:
V.Iterate (Print_Element'Access);
V.Iterate (Print_Element'Access);
end Vector_Example;</lang>
end Vector_Example;</syntaxhighlight>


=={{header|Aikido}}==
=={{header|Aikido}}==
Aikido's <code>foreach</code> loop allows iteration through multiple value types.
Aikido's <code>foreach</code> loop allows iteration through multiple value types.
===strings===
===strings===
<lang aikido>var str = "hello world"
<syntaxhighlight lang="aikido">var str = "hello world"
foreach ch str { // you can also use an optional 'in'
foreach ch str { // you can also use an optional 'in'
println (ch) // one character at a time
println (ch) // one character at a time
}</lang>
}</syntaxhighlight>
===vectors===
===vectors===
<lang aikido>var vec = [1,2,3,4]
<syntaxhighlight lang="aikido">var vec = [1,2,3,4]
foreach v vec { // you can also use an optional 'in'
foreach v vec { // you can also use an optional 'in'
println (v)
println (v)
}</lang>
}</syntaxhighlight>
===maps===
===maps===
<lang aikido>var cities = {"San Ramon": 50000, "Walnut Creek": 70000, "San Francisco": 700000} // map literal
<syntaxhighlight lang="aikido">var cities = {"San Ramon": 50000, "Walnut Creek": 70000, "San Francisco": 700000} // map literal
foreach city cities {
foreach city cities {
println (city.first + " has population " + city.second)
println (city.first + " has population " + city.second)
}</lang>
}</syntaxhighlight>
===integers===
===integers===
<lang aikido>foreach i 100 {
<syntaxhighlight lang="aikido">foreach i 100 {
println (i) // prints values 0..99
println (i) // prints values 0..99
}
}
Line 193: Line 193:
foreach i a..b {
foreach i a..b {
println (i) // prints values from a to b (20..10)
println (i) // prints values from a to b (20..10)
}</lang>
}</syntaxhighlight>
===Objects===
===Objects===
Aikido allows definition of a <code>foreach</code> operator for an object. In this example we define a single linked list and a foreach operator to iterate through it
Aikido allows definition of a <code>foreach</code> operator for an object. In this example we define a single linked list and a foreach operator to iterate through it
<lang aikido>class List {
<syntaxhighlight lang="aikido">class List {
class Element (public data) {
class Element (public data) {
public var next = null
public var next = null
Line 229: Line 229:
foreach n list {
foreach n list {
println (n)
println (n)
}</lang>
}</syntaxhighlight>
===Coroutines===
===Coroutines===
Aikido supports coroutines. The foreach operator may be used to iterate thorough the generated values.
Aikido supports coroutines. The foreach operator may be used to iterate thorough the generated values.
<lang aikido>// coroutine to generate the squares of a sequence of numbers
<syntaxhighlight lang="aikido">// coroutine to generate the squares of a sequence of numbers
function squares (start, end) {
function squares (start, end) {
for (var i = start ; i < end ; i++) {
for (var i = start ; i < end ; i++) {
Line 244: Line 244:
foreach s squares (start, end) {
foreach s squares (start, end) {
println (s)
println (s)
}</lang>
}</syntaxhighlight>
===Files===
===Files===
If you open a file you can iterate through all the lines
If you open a file you can iterate through all the lines
<lang aikido>var s = openin ("input.txt")
<syntaxhighlight lang="aikido">var s = openin ("input.txt")
foreach line s {
foreach line s {
print (line)
print (line)
}</lang>
}</syntaxhighlight>
===Enumerations===
===Enumerations===
<lang aikido>enum Color {
<syntaxhighlight lang="aikido">enum Color {
RED, GREEN, BLUE
RED, GREEN, BLUE
}
}
Line 258: Line 258:
foreach color Color {
foreach color Color {
println (color)
println (color)
}</lang>
}</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime># iterate over a list of integers
<syntaxhighlight lang="aime"># iterate over a list of integers
integer i, v;
integer i, v;


for (i, v in list(2, 3, 5, 7, 11, 13, 17, 18)) {
for (i, v in list(2, 3, 5, 7, 11, 13, 17, 18)) {
}</lang>
}</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 271: Line 271:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>[]UNION(STRING, INT, PROC(REF FILE)VOID) collection = ("Mary","Had",1,"little","lamb.",new line);
<syntaxhighlight lang="algol68">[]UNION(STRING, INT, PROC(REF FILE)VOID) collection = ("Mary","Had",1,"little","lamb.",new line);


FOR index FROM LWB collection TO UPB collection DO
FOR index FROM LWB collection TO UPB collection DO
print((collection[index]," "))
print((collection[index]," "))
OD</lang>
OD</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 284: Line 284:
<br>
<br>
<br>[[ALGOL 68RS]] and [[Algol68toc]] have a FORALL loop, the following is equivalent to the example above:
<br>[[ALGOL 68RS]] and [[Algol68toc]] have a FORALL loop, the following is equivalent to the example above:
<lang algol68>FORALL index IN collection DO
<syntaxhighlight lang="algol68">FORALL index IN collection DO
print((collection[index]," "))
print((collection[index]," "))
OD</lang>
OD</syntaxhighlight>


=={{header|AmigaE}}==
=={{header|AmigaE}}==
<lang amigae>PROC main()
<syntaxhighlight lang="amigae">PROC main()
DEF a_list : PTR TO LONG, a
DEF a_list : PTR TO LONG, a
a_list := [10, 12, 14]
a_list := [10, 12, 14]
Line 297: Line 297:
-> if the "action" fits a single statement, we can do instead
-> if the "action" fits a single statement, we can do instead
ForAll({a}, a_list, `WriteF('\d\n', a))
ForAll({a}, a_list, `WriteF('\d\n', a))
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|Apex}}==
=={{header|Apex}}==
<syntaxhighlight lang="apex">
<lang Apex>
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


Line 306: Line 306:
System.debug(i);
System.debug(i);
}
}
</syntaxhighlight>
</lang>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang AppleScript>repeat with fruit in {"Apple", "Orange", "Banana"}
<syntaxhighlight lang="applescript">repeat with fruit in {"Apple", "Orange", "Banana"}
log contents of fruit
log contents of fruit
end repeat</lang>
end repeat</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>arr: ["one" "two" "three"]
<syntaxhighlight lang="rebol">arr: ["one" "two" "three"]


dict: #[
dict: #[
Line 326: Line 326:


loop dict [key val]->
loop dict [key val]->
print [key "=>" val]</lang>
print [key "=>" val]</syntaxhighlight>
{{out}}
{{out}}
<pre>one
<pre>one
Line 336: Line 336:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>string = mary,had,a,little,lamb
<syntaxhighlight lang="autohotkey">string = mary,had,a,little,lamb
Loop, Parse, string, `,
Loop, Parse, string, `,
MsgBox %A_LoopField%</lang>
MsgBox %A_LoopField%</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
The <code>for (element_index in array)</code> can be used, but it does not give elements' indexes in the order inside the array (AWK indexes in array are indeed more like hashes).
The <code>for (element_index in array)</code> can be used, but it does not give elements' indexes in the order inside the array (AWK indexes in array are indeed more like hashes).
<lang awk>
<syntaxhighlight lang="awk">
BEGIN {
BEGIN {
split("Mary had a little lamb", strs, " ")
split("Mary had a little lamb", strs, " ")
Line 348: Line 348:
print strs[el]
print strs[el]
}
}
}</lang>
}</syntaxhighlight>
If elements must be returned in some order, keys must be generated in that order.
If elements must be returned in some order, keys must be generated in that order.
In the example above the array is filled through the split function,
In the example above the array is filled through the split function,
Line 354: Line 354:
So to iterate over the array's elements in the ''right'' order,
So to iterate over the array's elements in the ''right'' order,
a normal loop can be used:
a normal loop can be used:
<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
n = split("Mary had a little lamb", strs, " ")
n = split("Mary had a little lamb", strs, " ")
for(i=1; i <= n; i++) {
for(i=1; i <= n; i++) {
print strs[i]
print strs[i]
}
}
}</lang>
}</syntaxhighlight>


Note that in awk, foreach loops can only be performed against an associative container.
Note that in awk, foreach loops can only be performed against an associative container.
It is not possible to loop against an explicit list, so the following will not work:
It is not possible to loop against an explicit list, so the following will not work:


<lang awk># This will not work
<syntaxhighlight lang="awk"># This will not work
BEGIN {
BEGIN {
for (el in "apples","bananas","cherries") {
for (el in "apples","bananas","cherries") {
print "I like " el
print "I like " el
}
}
}</lang>
}</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 376: Line 376:
BaCon includes support for ''delimited strings''. Delimited strings form a type of collection. Along with this support is a <code>for in</code> loop. Not quite a <code>for each</code> but pretty close.
BaCon includes support for ''delimited strings''. Delimited strings form a type of collection. Along with this support is a <code>for in</code> loop. Not quite a <code>for each</code> but pretty close.


<lang freebasic>OPTION COLLAPSE TRUE
<syntaxhighlight lang="freebasic">OPTION COLLAPSE TRUE
FOR x$ IN "Hello cruel world"
FOR x$ IN "Hello cruel world"
PRINT x$
PRINT x$
Line 383: Line 383:
FOR y$ IN "1,2,\"3,4\",5" STEP ","
FOR y$ IN "1,2,\"3,4\",5" STEP ","
PRINT y$
PRINT y$
NEXT</lang>
NEXT</syntaxhighlight>


{{out}}
{{out}}
Line 400: Line 400:
==={{header|BASIC256}}===
==={{header|BASIC256}}===
BASIC-256 does not have a FOR EACH type statement. Use a FOR loop to iterate through an array by index.
BASIC-256 does not have a FOR EACH type statement. Use a FOR loop to iterate through an array by index.
<lang BASIC256>DIM collection$(1)
<syntaxhighlight lang="basic256">DIM collection$(1)
collection$ = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }
collection$ = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }


Line 406: Line 406:
PRINT collection$[i]+ " ";
PRINT collection$[i]+ " ";
NEXT i
NEXT i
PRINT</lang>
PRINT</syntaxhighlight>
Output:
Output:
<pre>The quick brown fox jumps over the lazy dog.</pre>
<pre>The quick brown fox jumps over the lazy dog.</pre>
Line 412: Line 412:
==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM collection$(8)
<syntaxhighlight lang="bbcbasic"> DIM collection$(8)
collection$() = "The", "quick", "brown", "fox", "jumps", \
collection$() = "The", "quick", "brown", "fox", "jumps", \
\ "over", "the", "lazy", "dog."
\ "over", "the", "lazy", "dog."
Line 419: Line 419:
PRINT collection$(index%) " ";
PRINT collection$(index%) " ";
NEXT
NEXT
PRINT</lang>
PRINT</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
Commodore BASIC too does not have a FOR-EACH construct. FOR loop is used to iterate through a string array by index. READ-DATA is used to fill up the string array
Commodore BASIC too does not have a FOR-EACH construct. FOR loop is used to iterate through a string array by index. READ-DATA is used to fill up the string array
<lang qbasic>10 DIM A$(9) :REM DECLARE STRING ARRAY
<syntaxhighlight lang="qbasic">10 DIM A$(9) :REM DECLARE STRING ARRAY
20 REM *** FILL ARRAY WITH WORDS ***
20 REM *** FILL ARRAY WITH WORDS ***
30 FOR I = 0 TO 8
30 FOR I = 0 TO 8
Line 433: Line 433:
90 NEXT
90 NEXT
100 END
100 END
1000 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</lang>
1000 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</syntaxhighlight>


==={{header|Creative Basic}}===
==={{header|Creative Basic}}===
<lang Creative Basic>DEF AnArray[11]:INT
<syntaxhighlight lang="creative basic">DEF AnArray[11]:INT


AnArray=0,1,2,3,4,5,6,7,8,9,10
AnArray=0,1,2,3,4,5,6,7,8,9,10
Line 455: Line 455:
'because this is a console only program.
'because this is a console only program.
END
END
</syntaxhighlight>
</lang>


==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
<lang freebasic>' FB 1.05.0
<syntaxhighlight lang="freebasic">' FB 1.05.0


' FreeBASIC doesn't have a foreach loop but it's easy to manufacture one using macros
' FreeBASIC doesn't have a foreach loop but it's easy to manufacture one using macros
Line 475: Line 475:


Print
Print
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 484: Line 484:
==={{header|Gambas}}===
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=cb94500c68749f6f93915f3f10de5a03 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=cb94500c68749f6f93915f3f10de5a03 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siInput As Short[] = [1, 8, 0, 6, 4, 7, 3, 2, 5, 9]
Dim siInput As Short[] = [1, 8, 0, 6, 4, 7, 3, 2, 5, 9]
Dim siTemp As Short
Dim siTemp As Short
Line 492: Line 492:
Next
Next


End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 499: Line 499:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 STRING COLLECTION$(1 TO 9)*8
<syntaxhighlight lang="is-basic">100 STRING COLLECTION$(1 TO 9)*8
110 LET I=1
110 LET I=1
120 DO
120 DO
Line 508: Line 508:
170 PRINT COLLECTION$(J);" ";
170 PRINT COLLECTION$(J);" ";
180 NEXT
180 NEXT
190 DATA The,quick,brown,fox,jumps,over,the,lazy,dog.</lang>
190 DATA The,quick,brown,fox,jumps,over,the,lazy,dog.</syntaxhighlight>


==={{header|IWBASIC}}===
==={{header|IWBASIC}}===
'''Linked List'''
'''Linked List'''
<lang IWBASIC>DEF AList:POINTER
<syntaxhighlight lang="iwbasic">DEF AList:POINTER


AList=ListCreate()
AList=ListCreate()
Line 543: Line 543:


'Because this is a console only program.
'Because this is a console only program.
END</lang>
END</syntaxhighlight>


'''An Array'''
'''An Array'''
<lang IWBASIC>DEF AnArray[11]:INT
<syntaxhighlight lang="iwbasic">DEF AnArray[11]:INT


AnArray=0,1,2,3,4,5,6,7,8,9,10
AnArray=0,1,2,3,4,5,6,7,8,9,10
Line 563: Line 563:
'Because this is a console only program.
'Because this is a console only program.
END
END
</syntaxhighlight>
</lang>


==={{header|Lambdatalk}}===
==={{header|Lambdatalk}}===
<lang scheme>
<syntaxhighlight lang="scheme">
{def collection alpha beta gamma delta}
{def collection alpha beta gamma delta}
-> collection
-> collection
Line 592: Line 592:
delta
delta


</syntaxhighlight>
</lang>


==={{header|Liberty BASIC}}===
==={{header|Liberty BASIC}}===
The most natural way is to use a csv list with a sentinel value.
The most natural way is to use a csv list with a sentinel value.
<lang lb>in$ ="Not,Hardly,Just,Adequately,Quite,Really,Very,Fantastically,xyzzy"
<syntaxhighlight lang="lb">in$ ="Not,Hardly,Just,Adequately,Quite,Really,Very,Fantastically,xyzzy"
element$ =""
element$ =""
i =1 ' used to point to successive elements
i =1 ' used to point to successive elements
Line 607: Line 607:
loop until 1 =2
loop until 1 =2


end</lang>
end</syntaxhighlight>
Not good!
Not good!
Hardly good!
Hardly good!
Line 618: Line 618:


==={{header|NS-HUBASIC}}===
==={{header|NS-HUBASIC}}===
<lang NS-HUBASIC>10 DIM A$(9) : REM DECLARE STRING ARRAY
<syntaxhighlight lang="ns-hubasic">10 DIM A$(9) : REM DECLARE STRING ARRAY
20 REM ADD DATA TO ARRAY AND PRINT ARRAY CONTENTS
20 REM ADD DATA TO ARRAY AND PRINT ARRAY CONTENTS
30 FOR I=0 TO 8
30 FOR I=0 TO 8
Line 624: Line 624:
50 PRINT A$(I)" ";
50 PRINT A$(I)" ";
60 NEXT
60 NEXT
70 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</lang>
70 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</syntaxhighlight>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
Works for LinkedLists and Maps
Works for LinkedLists and Maps
<lang PureBasic>ForEach element()
<syntaxhighlight lang="purebasic">ForEach element()
PrintN(element())
PrintN(element())
Next</lang>
Next</syntaxhighlight>


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
<lang runbasic>t$={Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday"
<syntaxhighlight lang="runbasic">t$={Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday"


while word$(t$,i+1,",") <> ""
while word$(t$,i+1,",") <> ""
i = i + 1
i = i + 1
print word$(t$,i,",")
print word$(t$,i,",")
wend</lang>
wend</syntaxhighlight>


==={{header|TI-89 BASIC}}===
==={{header|TI-89 BASIC}}===
<lang ti89b>Local i,strs
<syntaxhighlight lang="ti89b">Local i,strs
Define strs = {"Lorem","ipsum","dolor"}
Define strs = {"Lorem","ipsum","dolor"}
For i, 1, dim(strs)
For i, 1, dim(strs)
Disp strs[i]
Disp strs[i]
EndFor</lang>
EndFor</syntaxhighlight>


==={{header|VBA}}===
==={{header|VBA}}===
<lang VB>Public Sub LoopsForeach()
<syntaxhighlight lang="vb">Public Sub LoopsForeach()
Dim FruitArray() As Variant
Dim FruitArray() As Variant
Dim Fruit As Variant
Dim Fruit As Variant
Line 660: Line 660:
Debug.Print Fruit
Debug.Print Fruit
Next Fruit
Next Fruit
End Sub</lang>
End Sub</syntaxhighlight>


==={{header|VBScript}}===
==={{header|VBScript}}===
<lang vbscript>items = Array("Apple", "Orange", "Banana")
<syntaxhighlight lang="vbscript">items = Array("Apple", "Orange", "Banana")


For Each x In items
For Each x In items
WScript.Echo x
WScript.Echo x
Next</lang>
Next</syntaxhighlight>


==={{header|Visual Basic .NET}}===
==={{header|Visual Basic .NET}}===
<lang vbnet>Dim list As New List(Of String)
<syntaxhighlight lang="vbnet">Dim list As New List(Of String)
list.Add("Car")
list.Add("Car")
list.Add("Boat")
list.Add("Boat")
Line 677: Line 677:
For Each item In list
For Each item In list
Console.WriteLine(item)
Console.WriteLine(item)
Next</lang>
Next</syntaxhighlight>




==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang Yabasic>//Yabasic tampoco tiene una construcción ForEach.
<syntaxhighlight lang="yabasic">//Yabasic tampoco tiene una construcción ForEach.
//Mediante un bucle FOR iteramos a través de una matriz por índice.
//Mediante un bucle FOR iteramos a través de una matriz por índice.
//READ-DATA se usa para rellenar la matriz
//READ-DATA se usa para rellenar la matriz
Line 695: Line 695:
next each
next each
print
print
end</lang>
end</syntaxhighlight>




Line 702: Line 702:


'''Direct usage:'''
'''Direct usage:'''
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
for %%A in (This is a sample collection) do (
for %%A in (This is a sample collection) do (
echo %%A
echo %%A
)</lang>
)</syntaxhighlight>
'''Using a Collection Variable:'''
'''Using a Collection Variable:'''
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
set "collection=This is a sample collection"
set "collection=This is a sample collection"
for %%A in (%collection%) do (
for %%A in (%collection%) do (
echo %%A
echo %%A
)</lang>
)</syntaxhighlight>
{{Out|They have the Same Output}}
{{Out|They have the Same Output}}
<pre>This
<pre>This
Line 721: Line 721:
=={{header|bc}}==
=={{header|bc}}==
There is no "for each"-loop in bc. For accessing each element of an array (the only collection-like type) one uses a straightforward for-loop.
There is no "for each"-loop in bc. For accessing each element of an array (the only collection-like type) one uses a straightforward for-loop.
<lang bc>a[0] = .123
<syntaxhighlight lang="bc">a[0] = .123
a[1] = 234
a[1] = 234
a[3] = 95.6
a[3] = 95.6
for (i = 0; i < 4; i++) {
for (i = 0; i < 4; i++) {
a[i]
a[i]
}</lang>
}</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Bracmat has a more or less traditional 'while' loop (<code>whl'<i>expression</i></code>) which was introduced rather late in the history of Bracmat. Before that, tail recursion was a way to repeat something.
Bracmat has a more or less traditional 'while' loop (<code>whl'<i>expression</i></code>) which was introduced rather late in the history of Bracmat. Before that, tail recursion was a way to repeat something.
But let us make a list first:
But let us make a list first:
<lang bracmat> ( list
<syntaxhighlight lang="bracmat"> ( list
= Afrikaans
= Afrikaans
Ελληνικά
Ελληνικά
Line 737: Line 737:
മലയാളം
മലയാളം
ئۇيغۇرچە
ئۇيغۇرچە
)</lang>
)</syntaxhighlight>
The 'while' solution. Use an auxiliary variable <code>L</code> that gets its head chopped off until nothing is left:
The 'while' solution. Use an auxiliary variable <code>L</code> that gets its head chopped off until nothing is left:
<lang bracmat> !list:?L
<syntaxhighlight lang="bracmat"> !list:?L
& whl'(!L:%?language ?L&out$!language)</lang>
& whl'(!L:%?language ?L&out$!language)</syntaxhighlight>
The tail-recursive solution. When the auxiliary variable is reduced to nothing, the loop fails. By adding the <code>~</code> flag to the initial invocation, failure is turned into success. This solution benefits from tail recursion optimization.
The tail-recursive solution. When the auxiliary variable is reduced to nothing, the loop fails. By adding the <code>~</code> flag to the initial invocation, failure is turned into success. This solution benefits from tail recursion optimization.
<lang bracmat> !list:?L
<syntaxhighlight lang="bracmat"> !list:?L
& ( loop
& ( loop
= !L:%?language ?L
= !L:%?language ?L
Line 748: Line 748:
& !loop
& !loop
)
)
& ~!loop</lang>
& ~!loop</syntaxhighlight>
A completely different way of iteration is by using a pattern that matches an element in the list, does something useful as a side effect and then fails, forcing bracmat to backtrack and try the next element in the list. The <code>@</code> flag matches at most one element. The <code>%</code> flag matches at least one element. Together they ensure that exactly one language name is assigned to the variable <code>language</code>. After all elements have been done, control is passed to the rhs of the <code>|</code> operator.
A completely different way of iteration is by using a pattern that matches an element in the list, does something useful as a side effect and then fails, forcing bracmat to backtrack and try the next element in the list. The <code>@</code> flag matches at most one element. The <code>%</code> flag matches at least one element. Together they ensure that exactly one language name is assigned to the variable <code>language</code>. After all elements have been done, control is passed to the rhs of the <code>|</code> operator.
<lang bracmat> ( !list
<syntaxhighlight lang="bracmat"> ( !list
: ? (%@?language&out$!language&~) ?
: ? (%@?language&out$!language&~) ?
|
|
)</lang>
)</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
C does not really have a native 'container' type, nor does it have a 'for each' type statement. The following shows how to loop through an array and print each element.
C does not really have a native 'container' type, nor does it have a 'for each' type statement. The following shows how to loop through an array and print each element.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
...
...


Line 766: Line 766:
for(ix=0; ix<LIST_SIZE; ix++) {
for(ix=0; ix<LIST_SIZE; ix++) {
printf("%s\n", list[ix]);
printf("%s\n", list[ix]);
}</lang>
}</syntaxhighlight>


The C language does, however, have a number of standard data structures that can be thought of as collections, and foreach can easily be made with a macro.<BR><BR>
The C language does, however, have a number of standard data structures that can be thought of as collections, and foreach can easily be made with a macro.<BR><BR>


C string as a collection of char
C string as a collection of char
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 789: Line 789:
return(0);
return(0);
}
}
</syntaxhighlight>
</lang>


C int array as a collection of int (array size known at compile-time)
C int array as a collection of int (array size known at compile-time)
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 809: Line 809:
return(0);
return(0);
}
}
</syntaxhighlight>
</lang>


Most general: string or array as collection (collection size known at run-time)
Most general: string or array as collection (collection size known at run-time)
: ''Note: idxtype can be removed and [http://gcc.gnu.org/onlinedocs/gcc/Typeof.html typeof(col&#91;0&#93;)] can be used in it's place with [[GCC]]''
: ''Note: idxtype can be removed and [http://gcc.gnu.org/onlinedocs/gcc/Typeof.html typeof(col&#91;0&#93;)] can be used in it's place with [[GCC]]''
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
Line 838: Line 838:
return(0);
return(0);
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>string[] things = {"Apple", "Banana", "Coconut"};
<syntaxhighlight lang="csharp">string[] things = {"Apple", "Banana", "Coconut"};


foreach (string thing in things)
foreach (string thing in things)
{
{
Console.WriteLine(thing);
Console.WriteLine(thing);
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
C++03 did not have a "for each" loop. The following is a generic loop which works with any standard container except for built-in arrays. The code snippet below assumes that the container type in question is typedef'd to <tt>container_type</tt> and the actual container object is named container.
C++03 did not have a "for each" loop. The following is a generic loop which works with any standard container except for built-in arrays. The code snippet below assumes that the container type in question is typedef'd to <tt>container_type</tt> and the actual container object is named container.
<lang cpp>for (container_type::iterator i = container.begin(); i != container.end(); ++i)
<syntaxhighlight lang="cpp">for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
{
std::cout << *i << "\n";
std::cout << *i << "\n";
}</lang>
}</syntaxhighlight>
However the idiomatic way to output a container would be
However the idiomatic way to output a container would be
<lang cpp>std::copy(container.begin(), container.end(),
<syntaxhighlight lang="cpp">std::copy(container.begin(), container.end(),
std::ostream_iterator<container_type::value_type>(std::cout, "\n"));</lang>
std::ostream_iterator<container_type::value_type>(std::cout, "\n"));</syntaxhighlight>
There's also an algorithm named <tt>for_each</tt>. However, you need a function or function object to use it, e.g.
There's also an algorithm named <tt>for_each</tt>. However, you need a function or function object to use it, e.g.
<lang cpp>void print_element(container_type::value_type const& v)
<syntaxhighlight lang="cpp">void print_element(container_type::value_type const& v)
{
{
std::cout << v << "\n";
std::cout << v << "\n";
Line 864: Line 864:


...
...
std::for_each(container.begin(), container.end(), print_element);</lang>
std::for_each(container.begin(), container.end(), print_element);</syntaxhighlight>
{{works with|C++11}}
{{works with|C++11}}
<lang cpp>for (auto element: container)
<syntaxhighlight lang="cpp">for (auto element: container)
{
{
std::cout << element << "\n";
std::cout << element << "\n";
}</lang>
}</syntaxhighlight>
Here <tt>container</tt> is the container variable, <tt>element</tt> is the loop variable (initialized with each container element in turn), and auto means that the compiler should determine the correct type of that variable automatically. If the type is expensive to copy, a const reference can be used instead:
Here <tt>container</tt> is the container variable, <tt>element</tt> is the loop variable (initialized with each container element in turn), and auto means that the compiler should determine the correct type of that variable automatically. If the type is expensive to copy, a const reference can be used instead:
<lang cpp>for (auto const& element: container)
<syntaxhighlight lang="cpp">for (auto const& element: container)
{
{
std::cout << element << "\n";
std::cout << element << "\n";
}</lang>
}</syntaxhighlight>
Of course the container elements can also be changed by using a non-const reference (provided the container isn't itself constant):
Of course the container elements can also be changed by using a non-const reference (provided the container isn't itself constant):
<lang cpp>for (auto&& element: container) //use a 'universal reference'
<syntaxhighlight lang="cpp">for (auto&& element: container) //use a 'universal reference'
{
{
element += 42;
element += 42;
}</lang>
}</syntaxhighlight>


=={{header|Chapel}}==
=={{header|Chapel}}==
<lang chapel>var food = ["Milk", "Bread", "Butter"];
<syntaxhighlight lang="chapel">var food = ["Milk", "Bread", "Butter"];
for f in food do writeln(f);</lang>
for f in food do writeln(f);</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(doseq [item collection] (println item))</lang>
<syntaxhighlight lang="lisp">(doseq [item collection] (println item))</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
Line 898: Line 898:
one needs to explicitly use the <code>elements</code> iterator.
one needs to explicitly use the <code>elements</code> iterator.


<lang clu>start_up = proc ()
<syntaxhighlight lang="clu">start_up = proc ()
po: stream := stream$primary_output()
po: stream := stream$primary_output()
Line 907: Line 907:
stream$putl(po, word)
stream$putl(po, word)
end
end
end start_up</lang>
end start_up</syntaxhighlight>


=={{header|CMake}}==
=={{header|CMake}}==
<lang cmake>set(list one.c two.c three.c)
<syntaxhighlight lang="cmake">set(list one.c two.c three.c)


foreach(file ${list})
foreach(file ${list})
message(${file})
message(${file})
endforeach(file)</lang>
endforeach(file)</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 920: Line 920:
{{trans|C#}}
{{trans|C#}}
{{works with|Visual COBOL}}
{{works with|Visual COBOL}}
<lang cobol>01 things occurs 3.
<syntaxhighlight lang="cobol">01 things occurs 3.
...
...
set content of things to ("Apple", "Banana", "Coconut")
set content of things to ("Apple", "Banana", "Coconut")
perform varying thing as string through things
perform varying thing as string through things
display thing
display thing
end-perform</lang>
end-perform</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
<lang cfm>
<syntaxhighlight lang="cfm">
<Cfloop list="Fee, Fi, Foe, Fum" index="i">
<Cfloop list="Fee, Fi, Foe, Fum" index="i">
<Cfoutput>#i#!</Cfoutput>
<Cfoutput>#i#!</Cfoutput>
</Cfloop>
</Cfloop>
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(loop for i in list do (print i))</lang>
<syntaxhighlight lang="lisp">(loop for i in list do (print i))</syntaxhighlight>
or
or
<lang lisp>(map nil #'print list)</lang>
<syntaxhighlight lang="lisp">(map nil #'print list)</syntaxhighlight>
or
or
<lang lisp>(dolist (x the-list) (print x))</lang>
<syntaxhighlight lang="lisp">(dolist (x the-list) (print x))</syntaxhighlight>
or
or
<lang lisp>(use-package :iterate)
<syntaxhighlight lang="lisp">(use-package :iterate)
(iter
(iter
(for x in the-list)
(for x in the-list)
(print x))</lang>
(print x))</syntaxhighlight>


=== Using DO ===
=== Using DO ===
<lang lisp>
<syntaxhighlight lang="lisp">
(let ((the-list '(1 7 "foo" 1 4))) ; Set the-list as the list
(let ((the-list '(1 7 "foo" 1 4))) ; Set the-list as the list
(do ((i the-list (rest i))) ; Initialize to the-list and set to rest on every loop
(do ((i the-list (rest i))) ; Initialize to the-list and set to rest on every loop
((null i)) ; Break condition
((null i)) ; Break condition
(print (first i)))) ; On every loop print list's first element
(print (first i)))) ; On every loop print list's first element
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 965: Line 965:
=={{header|D}}==
=={{header|D}}==
This works if ''collection'' is a string/array/associative array, or if implements an appropriate ''opApply'' function, or if it has the basic Range methods.
This works if ''collection'' is a string/array/associative array, or if implements an appropriate ''opApply'' function, or if it has the basic Range methods.
<lang d>import std.stdio: writeln;
<syntaxhighlight lang="d">import std.stdio: writeln;


void main() {
void main() {
Line 982: Line 982:
foreach (key, value; collection3)
foreach (key, value; collection3)
writeln(key, " ", value);
writeln(key, " ", value);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>A
<pre>A
Line 998: Line 998:


=={{header|Dao}}==
=={{header|Dao}}==
<lang dao>items = { 1, 2, 3 }
<syntaxhighlight lang="dao">items = { 1, 2, 3 }
for( item in items ) io.writeln( item )</lang>
for( item in items ) io.writeln( item )</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 1,005: Line 1,005:


Supports arrays (single, multidimensional, and dynamic), sets, strings, collections and any class or interface that implements GetEnumerator().
Supports arrays (single, multidimensional, and dynamic), sets, strings, collections and any class or interface that implements GetEnumerator().
<lang Delphi>program LoopForEach;
<syntaxhighlight lang="delphi">program LoopForEach;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,014: Line 1,014:
for s in 'Hello' do
for s in 'Hello' do
Writeln(s);
Writeln(s);
end.</lang>
end.</syntaxhighlight>
Output:
Output:
<pre>H
<pre>H
Line 1,023: Line 1,023:


=={{header|Dragon}}==
=={{header|Dragon}}==
<lang dragon>
<syntaxhighlight lang="dragon">
for value : array {
for value : array {
showln value
showln value
}
}
</syntaxhighlight>
</lang>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
<lang Dyalect>for i in [1,2,3] {
<syntaxhighlight lang="dyalect">for i in [1,2,3] {
print(i)
print(i)
}</lang>
}</syntaxhighlight>


This code would work for any type that has a method "iter" (returning an iterator). In fact a runtime environment silently calls this method for you here and creates an iterator out of an array. The code above is absolutely identical to:
This code would work for any type that has a method "iter" (returning an iterator). In fact a runtime environment silently calls this method for you here and creates an iterator out of an array. The code above is absolutely identical to:


<lang Dyalect>for i in [1,2,3].Iterate() {
<syntaxhighlight lang="dyalect">for i in [1,2,3].Iterate() {
print(i)
print(i)
}</lang>
}</syntaxhighlight>


This would perfectly work with any custom iterator as well:
This would perfectly work with any custom iterator as well:


<lang Dyalect>func myCollection() {
<syntaxhighlight lang="dyalect">func myCollection() {
yield 1
yield 1
yield 2
yield 2
Line 1,050: Line 1,050:
for i in myCollection() {
for i in myCollection() {
print(i)
print(i)
}</lang>
}</syntaxhighlight>


All three code samples would output:
All three code samples would output:
Line 1,059: Line 1,059:


=={{header|E}}==
=={{header|E}}==
<lang e>for e in theCollection {
<syntaxhighlight lang="e">for e in theCollection {
println(e)
println(e)
}</lang>
}</syntaxhighlight>
In E, the for ... in ... loop is also used for iterating over numeric ranges; see [[Loop/For#E]].
In E, the for ... in ... loop is also used for iterating over numeric ranges; see [[Loop/For#E]].


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define my-list '( albert simon antoinette))
(define my-list '( albert simon antoinette))
(for ((h my-list)) (write h))
(for ((h my-list)) (write h))
Line 1,079: Line 1,079:


;; etc ... for other collections like Streams, Hashes, Graphs, ...
;; etc ... for other collections like Streams, Hashes, Graphs, ...
</syntaxhighlight>
</lang>


=={{header|Efene}}==
=={{header|Efene}}==
Any data structure can be printed as a whole, preformated:
Any data structure can be printed as a whole, preformated:
<lang efene>io.format("~p~n", [Collection])</lang>
<syntaxhighlight lang="efene">io.format("~p~n", [Collection])</syntaxhighlight>
However, to iterate over each element of a list, Efene uses <tt>lists.map/2</tt>, except in the case of IO where <tt>lists.foreach/2</tt> has to be used as the evaluation order is defined to be the same as the order of the elements in the list.
However, to iterate over each element of a list, Efene uses <tt>lists.map/2</tt>, except in the case of IO where <tt>lists.foreach/2</tt> has to be used as the evaluation order is defined to be the same as the order of the elements in the list.
<lang efene>lists.foreach(fn (X) { io.format("~p~n", [X]) }, Collection)</lang>
<syntaxhighlight lang="efene">lists.foreach(fn (X) { io.format("~p~n", [X]) }, Collection)</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
{{works with|EiffelStudio|6.6 beta (with provisional loop syntax)}}
{{works with|EiffelStudio|6.6 beta (with provisional loop syntax)}}
The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword <code lang="eiffel">across</code>.
The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword <code lang="eiffel">across</code>.
<lang eiffel > across my_list as ic loop print (ic.item) end</lang>
<syntaxhighlight lang="eiffel "> across my_list as ic loop print (ic.item) end</syntaxhighlight>
The local entity <code lang="eiffel">ic</code> is an instance of the library class <code lang="eiffel">ITERATION_CURSOR</code>. The cursor's feature <code lang="eiffel">item</code> provides access to each structure element. Descendants of class <code lang="eiffel">ITERATION_CURSOR</code> can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (<code lang="eiffel">my_list</code> in the example) are based on classes that inherit from the library class <code lang="eiffel">ITERABLE</code>
The local entity <code lang="eiffel">ic</code> is an instance of the library class <code lang="eiffel">ITERATION_CURSOR</code>. The cursor's feature <code lang="eiffel">item</code> provides access to each structure element. Descendants of class <code lang="eiffel">ITERATION_CURSOR</code> can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (<code lang="eiffel">my_list</code> in the example) are based on classes that inherit from the library class <code lang="eiffel">ITERABLE</code>
===Boolean expression variant===
===Boolean expression variant===
Line 1,096: Line 1,096:


This iteration is a boolean expression which is true if all items in <code>my_list</code> have counts greater than three:
This iteration is a boolean expression which is true if all items in <code>my_list</code> have counts greater than three:
<lang eiffel> across my_list as ic all ic.item.count > 3 end</lang>
<syntaxhighlight lang="eiffel"> across my_list as ic all ic.item.count > 3 end</syntaxhighlight>
Whereas, the following is true if at least one item has a count greater than three:
Whereas, the following is true if at least one item has a count greater than three:
<lang eiffel> across my_list as ic some ic.item.count > 3 end</lang>
<syntaxhighlight lang="eiffel"> across my_list as ic some ic.item.count > 3 end</syntaxhighlight>


=={{header|Ela}}==
=={{header|Ela}}==
<lang ela>open monad io
<syntaxhighlight lang="ela">open monad io
each [] = do return ()
each [] = do return ()
each (x::xs) = do
each (x::xs) = do
putStrLn $ show x
putStrLn $ show x
each xs</lang>
each xs</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
Line 1,121: Line 1,121:
console.printLine:thing
console.printLine:thing
}
}
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(1)> list = [1,3.14,"abc",[3],{0,5}]
<syntaxhighlight lang="elixir">iex(1)> list = [1,3.14,"abc",[3],{0,5}]
[1, 3.14, "abc", [3], {0, 5}]
[1, 3.14, "abc", [3], {0, 5}]
iex(2)> Enum.each(list, fn x -> IO.inspect x end)
iex(2)> Enum.each(list, fn x -> IO.inspect x end)
Line 1,132: Line 1,132:
[3]
[3]
{0, 5}
{0, 5}
:ok</lang>
:ok</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
For a list either <code>dolist</code> macro
For a list either <code>dolist</code> macro


<lang Lisp>(dolist (x '(1 2 3 4))
<syntaxhighlight lang="lisp">(dolist (x '(1 2 3 4))
(message "x=%d" x))</lang>
(message "x=%d" x))</syntaxhighlight>


or <code>mapc</code> function
or <code>mapc</code> function


<lang Lisp>(mapc (lambda (x)
<syntaxhighlight lang="lisp">(mapc (lambda (x)
(message "x=%d" x))
(message "x=%d" x))
'(1 2 3 4))</lang>
'(1 2 3 4))</syntaxhighlight>


{{libheader|cl-lib}}
{{libheader|cl-lib}}


<lang Lisp>(cl-loop for x in '(1 2 3 4) do (message "x=%d" x))</lang>
<syntaxhighlight lang="lisp">(cl-loop for x in '(1 2 3 4) do (message "x=%d" x))</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Any data structure can be printed as a whole, preformated:
Any data structure can be printed as a whole, preformated:
<lang erlang>io:format("~p~n",[Collection]).</lang>
<syntaxhighlight lang="erlang">io:format("~p~n",[Collection]).</syntaxhighlight>
However, to iterate over each element of a list, Erlang uses <tt>lists:map/2</tt>, except in the case of IO where <tt>lists:foreach/2</tt> has to be used as the evaluation order is defined to be the same as the order of the elements in the list.
However, to iterate over each element of a list, Erlang uses <tt>lists:map/2</tt>, except in the case of IO where <tt>lists:foreach/2</tt> has to be used as the evaluation order is defined to be the same as the order of the elements in the list.
<lang erlang>lists:foreach(fun(X) -> io:format("~p~n",[X]) end, Collection).</lang>
<syntaxhighlight lang="erlang">lists:foreach(fun(X) -> io:format("~p~n",[X]) end, Collection).</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
It's an extension of 'standard' FOR loop: constant list must be explicit.
It's an extension of 'standard' FOR loop: constant list must be explicit.
<lang ERRE>
<syntaxhighlight lang="erre">
FOR INDEX$=("The","quick","brown","fox","jumps","over","the","lazy","dog.") DO
FOR INDEX$=("The","quick","brown","fox","jumps","over","the","lazy","dog.") DO
PRINT(INDEX$;" ";)
PRINT(INDEX$;" ";)
END FOR
END FOR
PRINT
PRINT
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
{{works with|OpenEuphoria}}
{{works with|OpenEuphoria}}
<syntaxhighlight lang="euphoria">
<lang Euphoria>
include std/console.e
include std/console.e


Line 1,192: Line 1,192:


if getc(0) then end if
if getc(0) then end if
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,233: Line 1,233:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
We can use ''for'' directly or list iteration.
We can use ''for'' directly or list iteration.
<lang fsharp>for i in [1 .. 10] do printfn "%d" i
<syntaxhighlight lang="fsharp">for i in [1 .. 10] do printfn "%d" i


List.iter (fun i -> printfn "%d" i) [1 .. 10]</lang>
List.iter (fun i -> printfn "%d" i) [1 .. 10]</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>{ 1 2 4 } [ . ] each</lang>
<syntaxhighlight lang="factor">{ 1 2 4 } [ . ] each</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Use <code>each</code> method to iterate over a collection of items in a <code>List</code>.
Use <code>each</code> method to iterate over a collection of items in a <code>List</code>.
<lang fantom>class Main
<syntaxhighlight lang="fantom">class Main
{
{
public static Void main ()
public static Void main ()
Line 1,252: Line 1,252:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Fennel}}==
=={{header|Fennel}}==
====sequential table====
====sequential table====
<lang fennel>(each [k v (ipairs [:apple :banana :orange])]
<syntaxhighlight lang="fennel">(each [k v (ipairs [:apple :banana :orange])]
(print k v))</lang>
(print k v))</syntaxhighlight>
{{out}}
{{out}}
<pre>1 apple
<pre>1 apple
Line 1,263: Line 1,263:
3 orange</pre>
3 orange</pre>
====key-value table====
====key-value table====
<lang fennel>(each [k v (pairs {:apple :x :banana 4 :orange 3})]
<syntaxhighlight lang="fennel">(each [k v (pairs {:apple :x :banana 4 :orange 3})]
(print k v))</lang>
(print k v))</syntaxhighlight>
{{out}}
{{out}}
<pre>apple x
<pre>apple x
Line 1,270: Line 1,270:
orange 3</pre>
orange 3</pre>
=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>create a 3 , 2 , 1 ,
<syntaxhighlight lang="forth">create a 3 , 2 , 1 ,
: .array ( a len -- )
: .array ( a len -- )
cells bounds do i @ . cell +loop ; \ 3 2 1</lang>
cells bounds do i @ . cell +loop ; \ 3 2 1</syntaxhighlight>
===FOREACH===
===FOREACH===
The thing about extensible languages is if you need FOREACH, you can have FOREACH.
The thing about extensible languages is if you need FOREACH, you can have FOREACH.
Line 1,278: Line 1,278:
If we apply an appropriate XT to all the elements of an array we have it.
If we apply an appropriate XT to all the elements of an array we have it.


<lang forth>: FOREACH ( array size XT --)
<syntaxhighlight lang="forth">: FOREACH ( array size XT --)
>R \ save execution token on return stack
>R \ save execution token on return stack
CELLS BOUNDS \ convert addr,len -> last,first addresses
CELLS BOUNDS \ convert addr,len -> last,first addresses
Line 1,297: Line 1,297:


\ Usage example:
\ Usage example:
A[] 10 ' ? FOREACH </lang>
A[] 10 ' ? FOREACH </syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>program main
<syntaxhighlight lang="fortran">program main


implicit none
implicit none
Line 1,315: Line 1,315:
write(*,'(A)') colors
write(*,'(A)') colors


end program main</lang>
end program main</syntaxhighlight>


=={{header|friendly interactive shell}}==
=={{header|friendly interactive shell}}==
Unlike, bash or csh, the PATH variable is automatically converted to real array.
Unlike, bash or csh, the PATH variable is automatically converted to real array.
<lang fishshell>for path in $PATH
<syntaxhighlight lang="fishshell">for path in $PATH
echo You have $path in PATH.
echo You have $path in PATH.
end</lang>
end</syntaxhighlight>


Sample output:
Sample output:
Line 1,331: Line 1,331:
=={{header|Frink}}==
=={{header|Frink}}==
Frink's <CODE>for</CODE> loop is actually a "for each" loop which can iterate over built-in collection types including arrays, sets, dictionaries, enumerating expressions, and Java types such as Map, Iterator, Enumeration, etc.
Frink's <CODE>for</CODE> loop is actually a "for each" loop which can iterate over built-in collection types including arrays, sets, dictionaries, enumerating expressions, and Java types such as Map, Iterator, Enumeration, etc.
<lang frink>
<syntaxhighlight lang="frink">
array = [1, 2, 3, 5, 7]
array = [1, 2, 3, 5, 7]
for n = array
for n = array
println[n]
println[n]
</syntaxhighlight>
</lang>


=={{header|GAP}}==
=={{header|GAP}}==


<lang gap>for p in AlternatingGroup(4) do
<syntaxhighlight lang="gap">for p in AlternatingGroup(4) do
Print(p, "\n");
Print(p, "\n");
od;
od;
Line 1,354: Line 1,354:
(1,3,4)
(1,3,4)
(1,2)(3,4)
(1,2)(3,4)
(1,4,2)</lang>
(1,4,2)</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<code>range</code> works with all of the built-in container-types. With one variable (''i''), it gives you the key/index of every item. With two variables (''i'', ''x''), it gives you both the key/index and value/item. For channels, only the single-variable variant is allowed.
<code>range</code> works with all of the built-in container-types. With one variable (''i''), it gives you the key/index of every item. With two variables (''i'', ''x''), it gives you both the key/index and value/item. For channels, only the single-variable variant is allowed.
<lang go>func printAll(values []int) {
<syntaxhighlight lang="go">func printAll(values []int) {
for i, x := range values {
for i, x := range values {
fmt.Printf("Item %d = %d\n", i, x)
fmt.Printf("Item %d = %d\n", i, x)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
"for" loop:
"for" loop:
<lang groovy>def beatles = ["John", "Paul", "George", "Ringo"]
<syntaxhighlight lang="groovy">def beatles = ["John", "Paul", "George", "Ringo"]


for(name in beatles) {
for(name in beatles) {
println name
println name
}</lang>
}</syntaxhighlight>
"each()" method:<br>
"each()" method:<br>
Though technically not a loop, most Groovy programmers would use the somewhat more terse "each()" method on the list itself in preference to the "for" loop construct.
Though technically not a loop, most Groovy programmers would use the somewhat more terse "each()" method on the list itself in preference to the "for" loop construct.
<lang groovy>beatles.each {
<syntaxhighlight lang="groovy">beatles.each {
println it
println it
}</lang>
}</syntaxhighlight>
Output (same for either):
Output (same for either):
<pre>John
<pre>John
Line 1,383: Line 1,383:


=={{header|Halon}}==
=={{header|Halon}}==
<lang halon>$things = ["Apple", "Banana", "Coconut"];
<syntaxhighlight lang="halon">$things = ["Apple", "Banana", "Coconut"];


foreach ($things as $thing) {
foreach ($things as $thing) {
echo $thing;
echo $thing;
}</lang>
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Monad (forM_)
<syntaxhighlight lang="haskell">import Control.Monad (forM_)
forM_ collect print</lang>
forM_ collect print</syntaxhighlight>
which is the same as
which is the same as
<lang haskell>mapM_ print collect</lang>
<syntaxhighlight lang="haskell">mapM_ print collect</syntaxhighlight>


=={{header|Haxe}}==
=={{header|Haxe}}==
<lang haxe>var a = [1, 2, 3, 4];
<syntaxhighlight lang="haxe">var a = [1, 2, 3, 4];


for (i in a)
for (i in a)
Sys.println(i);</lang>
Sys.println(i);</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>CHARACTER days="Monday Tuesday Wednesday Thursday Friday Saturday Sunday "
<syntaxhighlight lang="hicest">CHARACTER days="Monday Tuesday Wednesday Thursday Friday Saturday Sunday "


items = INDEX(days, ' ', 256) ! 256 = count option
items = INDEX(days, ' ', 256) ! 256 = count option
Line 1,408: Line 1,408:
EDIT(Text=days, ITeM=j, Parse=today)
EDIT(Text=days, ITeM=j, Parse=today)
WRITE() today
WRITE() today
ENDDO</lang>
ENDDO</syntaxhighlight>


=={{header|Hy}}==
=={{header|Hy}}==
<lang clojure>(for [x collection] (print x))</lang>
<syntaxhighlight lang="clojure">(for [x collection] (print x))</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
The example below X can be a list, string, table or other data type.
The example below X can be a list, string, table or other data type.
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
X := [1,2,3,-5,6,9]
X := [1,2,3,-5,6,9]
every x := !L do
every x := !L do
write(x)
write(x)
end</lang>
end</syntaxhighlight>
This loop can be written somewhat more concisely as:
This loop can be written somewhat more concisely as:
<lang Icon>every write(!L)</lang>
<syntaxhighlight lang="icon">every write(!L)</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<lang io>collection foreach(println)</lang>
<syntaxhighlight lang="io">collection foreach(println)</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang J>smoutput each i.10</lang>
<syntaxhighlight lang="j">smoutput each i.10</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java>Iterable<Type> collect;
<syntaxhighlight lang="java">Iterable<Type> collect;
...
...
for(Type i:collect){
for(Type i:collect){
System.out.println(i);
System.out.println(i);
}</lang>
}</syntaxhighlight>
This works for any array type as well as any type that implements the Iterable interface (including all Collections).
This works for any array type as well as any type that implements the Iterable interface (including all Collections).


{{works with|Java|1.8+}}
{{works with|Java|1.8+}}
<lang java>
<syntaxhighlight lang="java">
Iterable collect;
Iterable collect;
...
...
collect.forEach(o -> System.out.println(o));
collect.forEach(o -> System.out.println(o));
</syntaxhighlight>
</lang>
This works with any Iterable, but not with arrays.
This works with any Iterable, but not with arrays.


=={{header|JavaScript}}==
=={{header|JavaScript}}==
For arrays in ES5, we can use '''Array.forEach()''':
For arrays in ES5, we can use '''Array.forEach()''':
<lang JavaScript>"alpha beta gamma delta".split(" ").forEach(function (x) {
<syntaxhighlight lang="javascript">"alpha beta gamma delta".split(" ").forEach(function (x) {
console.log(x);
console.log(x);
});</lang>
});</syntaxhighlight>
though it will probably be more natural – dispensing with side-effects, and allowing for easier composition of nested functions – to simply use '''Array.map()''',
though it will probably be more natural – dispensing with side-effects, and allowing for easier composition of nested functions – to simply use '''Array.map()''',
<lang JavaScript>console.log("alpha beta gamma delta".split(" ").map(function (x) {
<syntaxhighlight lang="javascript">console.log("alpha beta gamma delta".split(" ").map(function (x) {
return x.toUpperCase(x);
return x.toUpperCase(x);
}).join("\n"));</lang>
}).join("\n"));</syntaxhighlight>
or, more flexibly, and with greater generality, obtain an accumulating fold from '''Array.reduce()'''
or, more flexibly, and with greater generality, obtain an accumulating fold from '''Array.reduce()'''
<lang JavaScript>console.log("alpha beta gamma delta".split(" ").reduce(function (a, x, i, lst) {
<syntaxhighlight lang="javascript">console.log("alpha beta gamma delta".split(" ").reduce(function (a, x, i, lst) {
return lst.length - i + ". " + x + "\n" + a;
return lst.length - i + ". " + x + "\n" + a;
}, ""));</lang>
}, ""));</syntaxhighlight>
More generally, the following works for any object, including an array. It iterates over the keys of an object.
More generally, the following works for any object, including an array. It iterates over the keys of an object.
<lang JavaScript>for (var a in o) {
<syntaxhighlight lang="javascript">for (var a in o) {
print(o[a]);
print(o[a]);
}</lang>
}</syntaxhighlight>
However, it has the often unwanted feature that it lists inherited properties and methods of objects as well as the ones directly set on the object -- consider whether to filter out such properties inside the loop, for example:
However, it has the often unwanted feature that it lists inherited properties and methods of objects as well as the ones directly set on the object -- consider whether to filter out such properties inside the loop, for example:
<lang JavaScript>for (var a in o) {
<syntaxhighlight lang="javascript">for (var a in o) {
if (o.hasOwnProperty(a)) {
if (o.hasOwnProperty(a)) {
print(o[a]);
print(o[a]);
}
}
}</lang>
}</syntaxhighlight>
{{works with|JavaScript|1.6}}
{{works with|JavaScript|1.6}}
;Deprecated
;Deprecated
There is also a <tt>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for_each...in for each in]</tt> construct that iterates over the values of an object:
There is also a <tt>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for_each...in for each in]</tt> construct that iterates over the values of an object:
<lang JavaScript>h = {"one":1, "two":2, "three":3}
<syntaxhighlight lang="javascript">h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for (x in h) print(x);
for each (y in h) print(y);</lang>
for each (y in h) print(y);</syntaxhighlight>
{{works with|ECMAScript|6th edition}}
{{works with|ECMAScript|6th edition}}
There is also a <tt>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of for of]</tt> construct that iterates over the values of an object:
There is also a <tt>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of for of]</tt> construct that iterates over the values of an object:
<lang JavaScript>h = {"one":1, "two":2, "three":3}
<syntaxhighlight lang="javascript">h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for (x in h) print(x);
for (y of h) print(y);</lang>
for (y of h) print(y);</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 1,485: Line 1,485:


In this section, the array defined by "example" is used as an example:
In this section, the array defined by "example" is used as an example:
<lang jq>def example: [1,2];</lang>
<syntaxhighlight lang="jq">def example: [1,2];</syntaxhighlight>
jq has two types of iterables -- JSON arrays and JSON objects. In both cases, the ".[]" filter may be used to iterate through the values, it being understand that for objects, the "values" are the values associated with the keys:
jq has two types of iterables -- JSON arrays and JSON objects. In both cases, the ".[]" filter may be used to iterate through the values, it being understand that for objects, the "values" are the values associated with the keys:
<lang jq>example | .[]
<syntaxhighlight lang="jq">example | .[]
# or equivalently: example[]</lang>
# or equivalently: example[]</syntaxhighlight>
<lang jq>{"a":1, "b":2} | .[]
<syntaxhighlight lang="jq">{"a":1, "b":2} | .[]
# or equivalently: {"a":1, "b":2}[]</lang>
# or equivalently: {"a":1, "b":2}[]</syntaxhighlight>


In both cases, the output is the stream consisting of the values 1 followed by 2.
In both cases, the output is the stream consisting of the values 1 followed by 2.


Sometimes it is necessary to use an alternative to ".[]". For example, one might want to generate an index along with the array elements. In such cases, the "range(m;n)" generator, which performs a similar role to C's "for(i=m; i<n; i++)", can be used for array. Here is how range/2 would be used to perform the task for an array:
Sometimes it is necessary to use an alternative to ".[]". For example, one might want to generate an index along with the array elements. In such cases, the "range(m;n)" generator, which performs a similar role to C's "for(i=m; i<n; i++)", can be used for array. Here is how range/2 would be used to perform the task for an array:
<lang jq>example | . as $a | range(0; length) | $a[.]</lang>
<syntaxhighlight lang="jq">example | . as $a | range(0; length) | $a[.]</syntaxhighlight>
For JSON objects, the corresponding technique involves using <tt>keys</tt>, e.g.
For JSON objects, the corresponding technique involves using <tt>keys</tt>, e.g.
<syntaxhighlight lang="jq">
<lang jq>
{"a":1, "b":2} | . as $o | keys | map( [., $o[.]] )
{"a":1, "b":2} | . as $o | keys | map( [., $o[.]] )
</syntaxhighlight>
</lang>
produces:
produces:
[["a",1],["b",2]]
[["a",1],["b",2]]
Line 1,507: Line 1,507:


To convert the constituent characters (or technically, codepoints) of a string into a stream of values, there are two techniques illustrated by these examples:
To convert the constituent characters (or technically, codepoints) of a string into a stream of values, there are two techniques illustrated by these examples:
<lang jq>"abc" | . as $s | range(0;length) | $s[.:.+1]
<syntaxhighlight lang="jq">"abc" | . as $s | range(0;length) | $s[.:.+1]


"abc" | explode | map( [.]|implode) | .[]</lang>
"abc" | explode | map( [.]|implode) | .[]</syntaxhighlight>


In both cases, the result is the stream of values: "a", "b", "c".
In both cases, the result is the stream of values: "a", "b", "c".
Line 1,515: Line 1,515:
=={{header|Jsish}}==
=={{header|Jsish}}==
Jsi supports ''for of'' for looping over element of an array.
Jsi supports ''for of'' for looping over element of an array.
<lang javascript>for (str of "alpha beta gamma delta".split(' ')) { puts(str); }</lang>
<syntaxhighlight lang="javascript">for (str of "alpha beta gamma delta".split(' ')) { puts(str); }</syntaxhighlight>


{{out}}
{{out}}
Line 1,525: Line 1,525:
=={{header|Julia}}==
=={{header|Julia}}==
{{trans|Python}}
{{trans|Python}}
<lang julia>for i in collection
<syntaxhighlight lang="julia">for i in collection
println(i)
println(i)
end</lang>
end</syntaxhighlight>
The Julia <code>for</code> statement is always a "foreach", and the built-in <code>start:end</code> or <code>start:step:end</code> "range" syntax can be used for iteration over arithmetic sequences. Many Julia objects support iteration: arrays and tuples iterate over each item, strings iterate over each character, dictionaries iterate over (key,value) pairs, numeric scalars provide a length-1 iteration over their value, and so on.
The Julia <code>for</code> statement is always a "foreach", and the built-in <code>start:end</code> or <code>start:step:end</code> "range" syntax can be used for iteration over arithmetic sequences. Many Julia objects support iteration: arrays and tuples iterate over each item, strings iterate over each character, dictionaries iterate over (key,value) pairs, numeric scalars provide a length-1 iteration over their value, and so on.


=={{header|K}}==
=={{header|K}}==
<lang K> {`0:$x} ' !10</lang>
<syntaxhighlight lang="k"> {`0:$x} ' !10</syntaxhighlight>
<lang K> _sin ' (1; 2; 3;)</lang>
<syntaxhighlight lang="k"> _sin ' (1; 2; 3;)</syntaxhighlight>


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>include ..\Utilitys.tlhy
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy


( -2 "field" 3.14159 ( "this" "that" ) ) len [get ?] for
( -2 "field" 3.14159 ( "this" "that" ) ) len [get ?] for


" " input</lang>
" " input</syntaxhighlight>
{{out}}
{{out}}
<pre>-2
<pre>-2
Line 1,547: Line 1,547:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,556: Line 1,556:
greek.forEach { print("$it ") }
greek.forEach { print("$it ") }
println()
println()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,568: Line 1,568:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def collection alpha beta gamma delta}
{def collection alpha beta gamma delta}
-> collection
-> collection
Line 1,594: Line 1,594:
delta
delta


</syntaxhighlight>
</lang>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: >>say.(*) . ;
<syntaxhighlight lang="lang5">: >>say.(*) . ;
5 iota >>say.</lang>
5 iota >>say.</syntaxhighlight>


=={{header|langur}}==
=={{header|langur}}==
A for in loop iterates over values and a for of loop iterates over indices.
A for in loop iterates over values and a for of loop iterates over indices.
<lang langur>for .i in [1, 2, 3] {
<syntaxhighlight lang="langur">for .i in [1, 2, 3] {
writeln .i
writeln .i
}
}
Line 1,618: Line 1,618:
for .i in .abc {
for .i in .abc {
writeln cp2s .i
writeln cp2s .i
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,635: Line 1,635:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>array(1,2,3) => foreach { stdoutnl(#1) }</lang>
<syntaxhighlight lang="lasso">array(1,2,3) => foreach { stdoutnl(#1) }</syntaxhighlight>
<lang Lasso>with i in array(1,2,3) do { stdoutnl(#i) }</lang>
<syntaxhighlight lang="lasso">with i in array(1,2,3) do { stdoutnl(#i) }</syntaxhighlight>


=={{header|LFE}}==
=={{header|LFE}}==


<lang lisp>(lists:foreach
<syntaxhighlight lang="lisp">(lists:foreach
(lambda (x)
(lambda (x)
(io:format "item: ~p~n" (list x)))
(io:format "item: ~p~n" (list x)))
(lists:seq 1 10))
(lists:seq 1 10))
</syntaxhighlight>
</lang>


=={{header|LIL}}==
=={{header|LIL}}==
<lang tcl># Loops/Foreach, in LIL
<syntaxhighlight lang="tcl"># Loops/Foreach, in LIL
set collection [list 1 2 "three"]
set collection [list 1 2 "three"]
append collection [list 4 5 six] # appended as a single item in collection
append collection [list 4 5 six] # appended as a single item in collection
Line 1,658: Line 1,658:
# each loop step quotes two copies of the item
# each loop step quotes two copies of the item
set newlist [foreach j $collection {quote $j $j}]
set newlist [foreach j $collection {quote $j $j}]
print "Result of second foreach: $newlist"</lang>
print "Result of second foreach: $newlist"</syntaxhighlight>


{{out}}
{{out}}
Line 1,671: Line 1,671:
=={{header|Lingo}}==
=={{header|Lingo}}==


<lang lingo>days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
<syntaxhighlight lang="lingo">days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
repeat with day in days
repeat with day in days
put day
put day
end repeat</lang>
end repeat</syntaxhighlight>
A callback-based forEach() can be implemented like this:
A callback-based forEach() can be implemented like this:
<lang lingo>----------------------------------------
<syntaxhighlight lang="lingo">----------------------------------------
-- One of the five native iterative methods defined in ECMAScript 5
-- One of the five native iterative methods defined in ECMAScript 5
-- @param {list} tList
-- @param {list} tList
Line 1,688: Line 1,688:
call(cbFunc, cbObj, tList[i], i, tList)
call(cbFunc, cbObj, tList[i], i, tList)
end repeat
end repeat
end</lang>
end</syntaxhighlight>
<lang lingo>days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
<syntaxhighlight lang="lingo">days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
forEach(days, #alert, _player)</lang>
forEach(days, #alert, _player)</syntaxhighlight>


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>"Lisaac loop foreach".split.foreach { word : STRING;
<syntaxhighlight lang="lisaac">"Lisaac loop foreach".split.foreach { word : STRING;
word.print;
word.print;
'\n'.print;
'\n'.print;
};</lang>
};</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
Livecode's ''for each'' operates on chunks which may be words, items, lines, tokens. Example is for items.<lang LiveCode>repeat for each item x in "red, green, blue"
Livecode's ''for each'' operates on chunks which may be words, items, lines, tokens. Example is for items.<syntaxhighlight lang="livecode">repeat for each item x in "red, green, blue"
put x & cr
put x & cr
--wait 100 millisec -- req'd if you want to see in the LC Message Box (akin to repl)
--wait 100 millisec -- req'd if you want to see in the LC Message Box (akin to repl)
end repeat</lang>
end repeat</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>foreach [red green blue] [print ?]</lang>
<syntaxhighlight lang="logo">foreach [red green blue] [print ?]</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Line 1,711: Line 1,711:


<code>pairs()</code> iterates over all entries in a table, but in no particular order:
<code>pairs()</code> iterates over all entries in a table, but in no particular order:
<lang lua>t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"}
<syntaxhighlight lang="lua">t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"}
for key, value in pairs(t) do
for key, value in pairs(t) do
print(value, key)
print(value, key)
end</lang>
end</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,728: Line 1,728:
<code>ipairs()</code> iterates over table entries with positive integer keys,
<code>ipairs()</code> iterates over table entries with positive integer keys,
and is used to iterate over lists in order.
and is used to iterate over lists in order.
<lang lua>l={'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', not_a_number='fooday', [0]='today', [-1]='yesterday' }
<syntaxhighlight lang="lua">l={'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', not_a_number='fooday', [0]='today', [-1]='yesterday' }
for key, value in ipairs(l) do
for key, value in ipairs(l) do
print(key, value)
print(key, value)
end</lang>
end</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,747: Line 1,747:
Iterators we have for Arrays, Inventories and Stacks (containers). Each(object Start to End), or Each(object 1 to -1) or Each(Object, 1,-1). We can use -2 for second from end item. We can use step inside while iterator {} using Iterator=Each(object, new_start, end_item). We can read cursor using ^. So Print k^, k2^, k1^ return positions (from 0 for inventories). We can use more than one iterators for an object.
Iterators we have for Arrays, Inventories and Stacks (containers). Each(object Start to End), or Each(object 1 to -1) or Each(Object, 1,-1). We can use -2 for second from end item. We can use step inside while iterator {} using Iterator=Each(object, new_start, end_item). We can read cursor using ^. So Print k^, k2^, k1^ return positions (from 0 for inventories). We can use more than one iterators for an object.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
\\ Inventories may have keys or keys/values
\\ Inventories may have keys or keys/values
Line 1,775: Line 1,775:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
for p in [2, 3, 5, 7] do
for p in [2, 3, 5, 7] do
print(p);
print(p);
end do;
end do;
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Foreach over list of strings
Foreach over list of strings
<lang mathematica>s = (StringSplit@Import["ExampleData/USConstitution.txt"])[[1;;7]];
<syntaxhighlight lang="mathematica">s = (StringSplit@Import["ExampleData/USConstitution.txt"])[[1;;7]];
Do[
Do[
Print@i,
Print@i,
{i, s}
{i, s}
]</lang>
]</syntaxhighlight>
Output:
Output:
<pre>We
<pre>We
Line 1,801: Line 1,801:


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang Matlab> list1 = [1,5,6,7,-7,-9];
<syntaxhighlight lang="matlab"> list1 = [1,5,6,7,-7,-9];
for k = list1, % list1 must be a row vector (i.e. array of size 1xn)
for k = list1, % list1 must be a row vector (i.e. array of size 1xn)
printf('%i\n',k)
printf('%i\n',k)
end; </lang>
end; </syntaxhighlight>
<lang Matlab> list2 = {'AA','BB','CC'};
<syntaxhighlight lang="matlab"> list2 = {'AA','BB','CC'};
for k = list2, % list2 must be a row vector (i.e. array of size 1xn)
for k = list2, % list2 must be a row vector (i.e. array of size 1xn)
printf('%s\n',k{1})
printf('%s\n',k{1})
end; </lang>
end; </syntaxhighlight>
A vectorized version of the code is
A vectorized version of the code is
<lang Matlab> printf('%d\n',list1);
<syntaxhighlight lang="matlab"> printf('%d\n',list1);
printf('%s\n',list2{:}); </lang>
printf('%s\n',list2{:}); </syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>for n in [2, 3, 5, 7] do print(n);</lang>
<syntaxhighlight lang="maxima">for n in [2, 3, 5, 7] do print(n);</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>
<syntaxhighlight lang="maxscript">
arr = for i in 1 to 50 collect ("Number: " + (random 10 99) as string)
arr = for i in 1 to 50 collect ("Number: " + (random 10 99) as string)
makeuniquearray arr
makeuniquearray arr
Line 1,823: Line 1,823:


for i in arr do print i as string
for i in arr do print i as string
</syntaxhighlight>
</lang>


=={{header|Metafont}}==
=={{header|Metafont}}==
If we have a list of arbitrary items, we can simply use for:
If we have a list of arbitrary items, we can simply use for:
<lang metafont>for x = "mary", "had", "a", "little", "lamb": message x; endfor
<syntaxhighlight lang="metafont">for x = "mary", "had", "a", "little", "lamb": message x; endfor
end</lang>
end</syntaxhighlight>
The list can be generated in place by any suitable macro or another loop... e.g. let us suppose we have things like <tt>a[n]</tt> defined (with maximum n being 10). Then
The list can be generated in place by any suitable macro or another loop... e.g. let us suppose we have things like <tt>a[n]</tt> defined (with maximum n being 10). Then
<lang metafont>for x = for i = 1 upto 9: a[i], endfor, a[10]: show x; endfor
<syntaxhighlight lang="metafont">for x = for i = 1 upto 9: a[i], endfor, a[10]: show x; endfor
end</lang>
end</syntaxhighlight>
works more like a <tt>foreach</tt>; we could make a macro to hide the strangeness of such a code.
works more like a <tt>foreach</tt>; we could make a macro to hide the strangeness of such a code.


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(1 2 3) 'puts foreach</lang>
<syntaxhighlight lang="min">(1 2 3) 'puts foreach</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==


<lang MiniScript>for i in collection
<syntaxhighlight lang="miniscript">for i in collection
print i
print i
end</lang>
end</syntaxhighlight>
The MiniScript <code>for</code> statement is always a "foreach", and the standard <code>range</code> intrinsic can be used for iteration over arithmetic sequences. All MiniScript collection types support iteration: lists iterate over each item, strings iterate over each character, and maps/objects iterate over (key,value) pairs.
The MiniScript <code>for</code> statement is always a "foreach", and the standard <code>range</code> intrinsic can be used for iteration over arithmetic sequences. All MiniScript collection types support iteration: lists iterate over each item, strings iterate over each character, and maps/objects iterate over (key,value) pairs.


=={{header|MOO}}==
=={{header|MOO}}==
<lang moo>things = {"Apple", "Banana", "Coconut"};
<syntaxhighlight lang="moo">things = {"Apple", "Banana", "Coconut"};
for thing in (things)
for thing in (things)
player:tell(thing);
player:tell(thing);
endfor</lang>
endfor</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
Like Python, Nanoquery supports for...in syntax for list types and strings.
Like Python, Nanoquery supports for...in syntax for list types and strings.
<lang Nanoquery>for item in collection
<syntaxhighlight lang="nanoquery">for item in collection
println item
println item
end</lang>
end</syntaxhighlight>
<strong>Some examples:</strong>
<strong>Some examples:</strong>
<lang Nanoquery>for n in {1,3,5,7,9}
<syntaxhighlight lang="nanoquery">for n in {1,3,5,7,9}
print n + " "
print n + " "
end
end
Line 1,866: Line 1,866:
print char
print char
end
end
println</lang>
println</syntaxhighlight>
{{out}}
{{out}}
<pre>1 3 5 7 9
<pre>1 3 5 7 9
Line 1,873: Line 1,873:
=={{header|Nemerle}}==
=={{header|Nemerle}}==
This works on anything which implements the IEnumerable interface.
This works on anything which implements the IEnumerable interface.
<lang Nemerle>def things = ["Apple", "Banana", "Coconut"];
<syntaxhighlight lang="nemerle">def things = ["Apple", "Banana", "Coconut"];


foreach (thing in things) WriteLine(thing.ToLower());
foreach (thing in things) WriteLine(thing.ToLower());
foreach (i in [5, 10 .. 100]) Write($"$i\t");</lang>
foreach (i in [5, 10 .. 100]) Write($"$i\t");</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary


Line 1,891: Line 1,891:
loop while daysi.hasNext
loop while daysi.hasNext
say daysi.next
say daysi.next
end</lang>
end</syntaxhighlight>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(map println '(Apple Banana Coconut))</lang>
<syntaxhighlight lang="newlisp">(map println '(Apple Banana Coconut))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>let list = ["lorem", "ipsum", "dolor"}
<syntaxhighlight lang="nim">let list = ["lorem", "ipsum", "dolor"}
for item in list:
for item in list:
echo item</lang>
echo item</syntaxhighlight>
{{out}}
{{out}}
<pre>lorem
<pre>lorem
Line 1,906: Line 1,906:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>fruits := ["Apple", "Banana", "Coconut"];
<syntaxhighlight lang="objeck">fruits := ["Apple", "Banana", "Coconut"];
each(i : fruits) {
each(i : fruits) {
fruits[i]->PrintLine();
fruits[i]->PrintLine();
};</lang>
};</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
Line 1,915: Line 1,915:
{{works with|GNUstep}}
{{works with|GNUstep}}
{{works with|Cocoa}}
{{works with|Cocoa}}
<lang objc>NSArray *collect;
<syntaxhighlight lang="objc">NSArray *collect;
//...
//...
for(Type i in collect){
for(Type i in collect){
NSLog(@"%@", i);
NSLog(@"%@", i);
}</lang>
}</syntaxhighlight>
''collect'' can be any object that adopts the NSFastEnumeration protocol.
''collect'' can be any object that adopts the NSFastEnumeration protocol.


Or (always using OpenStep compatible frameworks):
Or (always using OpenStep compatible frameworks):
{{works with|Objective-C|<2.0}}
{{works with|Objective-C|<2.0}}
<lang objc>NSArray *collect;
<syntaxhighlight lang="objc">NSArray *collect;
//...
//...
NSEnumerator *enm = [collect objectEnumerator];
NSEnumerator *enm = [collect objectEnumerator];
Line 1,930: Line 1,930:
while( (i = [enm nextObject]) ) {
while( (i = [enm nextObject]) ) {
// do something with object i
// do something with object i
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
List of integers:
List of integers:
<lang ocaml>List.iter
<syntaxhighlight lang="ocaml">List.iter
(fun i -> Printf.printf "%d\n" i)
(fun i -> Printf.printf "%d\n" i)
collect_list</lang>
collect_list</syntaxhighlight>
Array of integers:
Array of integers:
<lang ocaml>Array.iter
<syntaxhighlight lang="ocaml">Array.iter
(fun i -> Printf.printf "%d\n" i)
(fun i -> Printf.printf "%d\n" i)
collect_array</lang>
collect_array</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>a = [ 1,4,3,2 ];
<syntaxhighlight lang="octave">a = [ 1,4,3,2 ];
b = [ 1,2,3,4; 5,6,7,8 ];
b = [ 1,2,3,4; 5,6,7,8 ];
for v = a
for v = a
Line 1,950: Line 1,950:
for v = b
for v = b
disp(v); % v is the column vector [1;5], then [2;6] ...
disp(v); % v is the column vector [1;5], then [2;6] ...
endfor</lang>
endfor</syntaxhighlight>
We can also iterate over structures:
We can also iterate over structures:
<lang octave>x.a = [ 10, 11, 12 ];
<syntaxhighlight lang="octave">x.a = [ 10, 11, 12 ];
x.b = { "Cell", "ul", "ar" };
x.b = { "Cell", "ul", "ar" };
for [ val, key ] = x
for [ val, key ] = x
disp(key);
disp(key);
disp(val);
disp(val);
endfor</lang>
endfor</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: printMonths | m | Date.Months forEach: m [ m . ] ;</lang>
<syntaxhighlight lang="oforth">: printMonths | m | Date.Months forEach: m [ m . ] ;</syntaxhighlight>


But, apply can be used instead of a loop :
But, apply can be used instead of a loop :
<lang Oforth>#. Date.Months apply</lang>
<syntaxhighlight lang="oforth">#. Date.Months apply</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(for-each print '(1 3 4 2))
(for-each print '(1 3 4 2))
(print)
(print)
Line 1,974: Line 1,974:
'(5 6 7 8)
'(5 6 7 8)
'(a b x z))
'(a b x z))
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,991: Line 1,991:
The <tt>OVER</tt> loop control keyword is used to select each item in a collection in turn.
The <tt>OVER</tt> loop control keyword is used to select each item in a collection in turn.
Open Object Rexx allows the <tt>DO</tt> block structure keyword to be used to start a loop for backward compatibility with classic Rexx; the <tt>LOOP</tt> keyword is preferred here as it is self-documenting.
Open Object Rexx allows the <tt>DO</tt> block structure keyword to be used to start a loop for backward compatibility with classic Rexx; the <tt>LOOP</tt> keyword is preferred here as it is self-documenting.
<lang ooRexx>/* Rexx */
<syntaxhighlight lang="oorexx">/* Rexx */
say
say
say 'Loops/Foreach'
say 'Loops/Foreach'
Line 2,003: Line 2,003:
say out~strip()
say out~strip()


exit</lang>
exit</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 2,011: Line 2,011:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
MyList = [1 2 3 4]
MyList = [1 2 3 4]
in
in
Line 2,017: Line 2,017:


%% or:
%% or:
for E in MyList do {Show E} end</lang>
for E in MyList do {Show E} end</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>for(i=1,#v,print(v[i]))</lang>
<syntaxhighlight lang="parigp">for(i=1,#v,print(v[i]))</syntaxhighlight>


or (PARI/GP >= 2.4)
or (PARI/GP >= 2.4)


<lang parigp>apply(x->print(x),v)</lang>
<syntaxhighlight lang="parigp">apply(x->print(x),v)</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 2,030: Line 2,030:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>foreach my $i (@collection) {
<syntaxhighlight lang="perl">foreach my $i (@collection) {
print "$i\n";
print "$i\n";
}</lang>
}</syntaxhighlight>
The keyword <code>for</code> can be used instead of <code>foreach</code>. If a loop variable (here <code>$i</code>) is not given, then <code>$_</code> is used.
The keyword <code>for</code> can be used instead of <code>foreach</code>. If a loop variable (here <code>$i</code>) is not given, then <code>$_</code> is used.


A more compact notation using perl statement modifier:
A more compact notation using perl statement modifier:
<lang perl>print "$_\n" foreach @collection</lang>
<syntaxhighlight lang="perl">print "$_\n" foreach @collection</syntaxhighlight>


In perl, it is possible to loop against an explicit list, so there is no need to define a container:
In perl, it is possible to loop against an explicit list, so there is no need to define a container:


<lang perl>foreach $l ( "apples", "bananas", "cherries" ) {
<syntaxhighlight lang="perl">foreach $l ( "apples", "bananas", "cherries" ) {
print "I like $l\n";
print "I like $l\n";
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"field"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3.14159268979</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"this"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"that"</span><span style="color: #0000FF;">}}</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"field"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3.14159268979</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"this"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"that"</span><span style="color: #0000FF;">}}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHL}}==
=={{header|PHL}}==
<lang phl>var numbers = 1..10;
<syntaxhighlight lang="phl">var numbers = 1..10;


numbers each # (number) [
numbers each # (number) [
printf("%i\n", number);
printf("%i\n", number);
];</lang>
];</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>foreach ($collect as $i) {
<syntaxhighlight lang="php">foreach ($collect as $i) {
echo "$i\n";
echo "$i\n";
}
}
Line 2,066: Line 2,066:
foreach ($collect as $key => $i) {
foreach ($collect as $key => $i) {
echo "\$collect[$key] = $i\n";
echo "\$collect[$key] = $i\n";
}</lang>
}</syntaxhighlight>
<code>foreach</code> can also iterate over objects. By default it iterates over all visible fields of an object.
<code>foreach</code> can also iterate over objects. By default it iterates over all visible fields of an object.


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(mapc println '(Apple Banana Coconut))</lang>
<syntaxhighlight lang="picolisp">(mapc println '(Apple Banana Coconut))</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int main(){
<syntaxhighlight lang="pike">int main(){
array(int|string) collect = ({109, "Hi", "asdf", "qwerty"});
array(int|string) collect = ({109, "Hi", "asdf", "qwerty"});
foreach(collect, int|string elem){
foreach(collect, int|string elem){
write(elem + "\n");
write(elem + "\n");
}
}
}</lang>
}</syntaxhighlight>
Iterating over the keys and values of a mapping (dictionary):
Iterating over the keys and values of a mapping (dictionary):
<lang pike>int main(){
<syntaxhighlight lang="pike">int main(){
mapping(string:string) coll = (["foo":"asdf", "bar":"qwer", "quux":"zxcv"]);
mapping(string:string) coll = (["foo":"asdf", "bar":"qwer", "quux":"zxcv"]);
foreach (coll;string key;string val)
foreach (coll;string key;string val)
write(key+" --> "+val+"\n");
write(key+" --> "+val+"\n");
}
}
}</lang>
}</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>declare A(10) fixed binary;
<syntaxhighlight lang="pli">declare A(10) fixed binary;
do i = lbound(A,1) to hbound(A,1);
do i = lbound(A,1) to hbound(A,1);
put skip list (A(i));
put skip list (A(i));
end;</lang>
end;</syntaxhighlight>


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Create a list.
Create a list.
Line 2,129: Line 2,129:
Write the entry to the console.
Write the entry to the console.
Put the entry's next into the entry.
Put the entry's next into the entry.
Repeat.</lang>
Repeat.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,142: Line 2,142:
=={{header|Pop11}}==
=={{header|Pop11}}==
Iteration over list:
Iteration over list:
<lang pop11>lvars el, lst = [1 2 3 4 foo bar];
<syntaxhighlight lang="pop11">lvars el, lst = [1 2 3 4 foo bar];
for el in lst do
for el in lst do
printf(el,'%p\n');
printf(el,'%p\n');
endfor;</lang>
endfor;</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
The <code>forall</code> operator performs a loop over a collection (array, string or dictionary). Strings and arrays can be treated very much the same:
The <code>forall</code> operator performs a loop over a collection (array, string or dictionary). Strings and arrays can be treated very much the same:
<lang postscript>[1 5 3 2] { = } forall
<syntaxhighlight lang="postscript">[1 5 3 2] { = } forall
(abc) { = } forall</lang>
(abc) { = } forall</syntaxhighlight>
but dictionaries take a little more work since a key/value pair is pushed on the stack in each iteration:
but dictionaries take a little more work since a key/value pair is pushed on the stack in each iteration:
<lang postscript><</a 25 /b 42>> {
<syntaxhighlight lang="postscript"><</a 25 /b 42>> {
exch (Key: ) print
exch (Key: ) print
=
=
(Value: ) print
(Value: ) print
=
=
} forall</lang>
} forall</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$colors = "Black","Blue","Cyan","Gray","Green","Magenta","Red","White","Yellow",
$colors = "Black","Blue","Cyan","Gray","Green","Magenta","Red","White","Yellow",
"DarkBlue","DarkCyan","DarkGray","DarkGreen","DarkMagenta","DarkRed","DarkYellow"
"DarkBlue","DarkCyan","DarkGray","DarkGreen","DarkMagenta","DarkRed","DarkYellow"
Line 2,168: Line 2,168:
Write-Host "$color" -ForegroundColor $color
Write-Host "$color" -ForegroundColor $color
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,191: Line 2,191:
=={{header|Prolog}}==
=={{header|Prolog}}==
For example :
For example :
<lang Prolog>?- foreach(member(X, [red,green,blue,black,white]), writeln(X)).
<syntaxhighlight lang="prolog">?- foreach(member(X, [red,green,blue,black,white]), writeln(X)).
red
red
green
green
Line 2,198: Line 2,198:
white
white
true.
true.
</syntaxhighlight>
</lang>


=={{header|Python}}==
=={{header|Python}}==
<lang python>for i in collection:
<syntaxhighlight lang="python">for i in collection:
print i</lang>
print i</syntaxhighlight>


Note: The Python <code>for</code> statement is always a ''"foreach" ...'' and the <code>range()</code> and <code>xrange()</code> built-in functions are used to generate lists of indexes over which it will iterate as necessary. The majority of Python objects support iteration. Lists and tuples iterate over each item, strings iterate over each character, dictionaries iterate over keys, files iterate over lines, and so on.
Note: The Python <code>for</code> statement is always a ''"foreach" ...'' and the <code>range()</code> and <code>xrange()</code> built-in functions are used to generate lists of indexes over which it will iterate as necessary. The majority of Python objects support iteration. Lists and tuples iterate over each item, strings iterate over each character, dictionaries iterate over keys, files iterate over lines, and so on.


For example:
For example:
<lang python>lines = words = characters = 0
<syntaxhighlight lang="python">lines = words = characters = 0
f = open('somefile','r')
f = open('somefile','r')
for eachline in f:
for eachline in f:
Line 2,216: Line 2,216:
characters += 1
characters += 1


print lines, words, characters</lang>
print lines, words, characters</syntaxhighlight>


Whether <code>for</code> loops over the elements of the collection in order depends on the collection having an inherent order or not. Elements of strings (i.e. characters), tuples and lists, for example, are ordered but the order of elements in dictionaries and sets is not defined.
Whether <code>for</code> loops over the elements of the collection in order depends on the collection having an inherent order or not. Elements of strings (i.e. characters), tuples and lists, for example, are ordered but the order of elements in dictionaries and sets is not defined.
Line 2,222: Line 2,222:
One can loop over the key/value pairs of a dictionary in ''alphabetic'' or ''numeric'' key order by sorting the sequence of keys, provided that the keys are all of ''comparable'' types. In Python 3.x a sequence of mixed numeric and string elements is not sortable (at least not with the default invocation of <code>sorted()</code>), whereas in Python 2.x numeric types are sorted according to their string representation by default:
One can loop over the key/value pairs of a dictionary in ''alphabetic'' or ''numeric'' key order by sorting the sequence of keys, provided that the keys are all of ''comparable'' types. In Python 3.x a sequence of mixed numeric and string elements is not sortable (at least not with the default invocation of <code>sorted()</code>), whereas in Python 2.x numeric types are sorted according to their string representation by default:


<lang python>d = {3: "Earth", 1: "Mercury", 4: "Mars", 2: "Venus"}
<syntaxhighlight lang="python">d = {3: "Earth", 1: "Mercury", 4: "Mars", 2: "Venus"}
for k in sorted(d):
for k in sorted(d):
print("%i: %s" % (k, d[k]))
print("%i: %s" % (k, d[k]))
Line 2,228: Line 2,228:
d = {"London": "United Kingdom", "Berlin": "Germany", "Rome": "Italy", "Paris": "France"}
d = {"London": "United Kingdom", "Berlin": "Germany", "Rome": "Italy", "Paris": "France"}
for k in sorted(d):
for k in sorted(d):
print("%s: %s" % (k, d[k]))</lang>
print("%s: %s" % (k, d[k]))</syntaxhighlight>


{{works with|Python|2.x}}
{{works with|Python|2.x}}


<lang python>d = {"fortytwo": 42, 3.14159: "pi", 23: "twentythree", "zero": 0, 13: "thirteen"}
<syntaxhighlight lang="python">d = {"fortytwo": 42, 3.14159: "pi", 23: "twentythree", "zero": 0, 13: "thirteen"}
for k in sorted(d):
for k in sorted(d):
print("%s: %s" % (k, d[k]))</lang>
print("%s: %s" % (k, d[k]))</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery>$ "Sweet Boom Pungent Prickle Orange" nest$
<syntaxhighlight lang="quackery">$ "Sweet Boom Pungent Prickle Orange" nest$
witheach [ i times sp echo$ cr ]</lang>
witheach [ i times sp echo$ cr ]</syntaxhighlight>
{{Out}}
{{Out}}
<pre> Sweet
<pre> Sweet
Line 2,249: Line 2,249:


=={{header|R}}==
=={{header|R}}==
<lang R>a <- list("First", "Second", "Third", 5, 6)
<syntaxhighlight lang="r">a <- list("First", "Second", "Third", 5, 6)
for(i in a) print(i)</lang>
for(i in a) print(i)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,263: Line 2,263:
(for ([i sequence])
(for ([i sequence])
(displayln i))
(displayln i))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|2015.10-40}}
{{works with|Rakudo|2015.10-40}}
<lang perl6>say $_ for @collection;</lang>
<syntaxhighlight lang="raku" line>say $_ for @collection;</syntaxhighlight>
Raku leaves off the <tt>each</tt> from <tt>foreach</tt>, leaving us with <tt>for</tt> instead. The variable <tt>$_</tt> refers to the current element, unless you assign a name to it using <tt>-></tt>.
Raku leaves off the <tt>each</tt> from <tt>foreach</tt>, leaving us with <tt>for</tt> instead. The variable <tt>$_</tt> refers to the current element, unless you assign a name to it using <tt>-></tt>.
<lang perl6>for @collection -> $currentElement { say $currentElement; }</lang>
<syntaxhighlight lang="raku" line>for @collection -> $currentElement { say $currentElement; }</syntaxhighlight>
Raku will do it's best to put the topic at the right spot.
Raku will do it's best to put the topic at the right spot.
<lang perl6>.say for @collection;
<syntaxhighlight lang="raku" line>.say for @collection;
for @collection { .say };</lang>
for @collection { .say };</syntaxhighlight>
Iteration can also be done with hyperoperators. In this case it's a candidate for autothreading and as such, execution order may vary. The resulting list will be in order.
Iteration can also be done with hyperoperators. In this case it's a candidate for autothreading and as such, execution order may vary. The resulting list will be in order.
<lang perl6>@collection>>.say;
<syntaxhighlight lang="raku" line>@collection>>.say;
@collection>>.=&infix:<+>(2); # increment each element by 2</lang>
@collection>>.=&infix:<+>(2); # increment each element by 2</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Loop/Foreach"
Title: "Loop/Foreach"
URL: http://rosettacode.org/wiki/Loop/Foreach
URL: http://rosettacode.org/wiki/Loop/Foreach
Line 2,291: Line 2,291:
; the list from the current position.
; the list from the current position.


forall x [prin rejoin [x/1 "day "]] print ""</lang>
forall x [prin rejoin [x/1 "day "]] print ""</syntaxhighlight>
Output:
Output:
<pre>Sorkday Gunday Bluesday Nedsday Thirstday Frightday Caturday
<pre>Sorkday Gunday Bluesday Nedsday Thirstday Frightday Caturday
Line 2,297: Line 2,297:


=={{header|Red}}==
=={{header|Red}}==
<lang Red>>> blk: ["John" 23 "dave" 30 "bob" 20 "Jeff" 40]
<syntaxhighlight lang="red">>> blk: ["John" 23 "dave" 30 "bob" 20 "Jeff" 40]
>> foreach item blk [print item]
>> foreach item blk [print item]
John
John
Line 2,321: Line 2,321:
20 Jeff 40
20 Jeff 40
Jeff 40
Jeff 40
40</lang>
40</syntaxhighlight>


=={{header|ReScript}}==
=={{header|ReScript}}==
<lang ReScript>let fruits = ["apple", "banana", "coconut"]
<syntaxhighlight lang="rescript">let fruits = ["apple", "banana", "coconut"]


Js.Array2.forEach(fruits, f => Js.log(f))</lang>
Js.Array2.forEach(fruits, f => Js.log(f))</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
Retro has '''for-each''' combinators for operating on elements of various data structures.
Retro has '''for-each''' combinators for operating on elements of various data structures.


<lang Retro># Strings
<syntaxhighlight lang="retro"># Strings


This will display the ASCII code for each character in a string
This will display the ASCII code for each character in a string
Line 2,354: Line 2,354:
&Dictionary [ d:name s:put sp ] d:for-each
&Dictionary [ d:name s:put sp ] d:for-each
~~~
~~~
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>days = 'zuntik montik dinstik mitvokh donershtik fraytik shabes'
<syntaxhighlight lang="rexx">days = 'zuntik montik dinstik mitvokh donershtik fraytik shabes'


do j=1 for words(days) /*loop through days of the week. */
do j=1 for words(days) /*loop through days of the week. */
say word(days,j) /*display the weekday to screen. */
say word(days,j) /*display the weekday to screen. */
end /*j*/
end /*j*/
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
aList = "Welcome to the Ring Programming Language"
aList = "Welcome to the Ring Programming Language"
for n in aList
for n in aList
see n + nl
see n + nl
next
next
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>for i in collection do
<syntaxhighlight lang="ruby">for i in collection do
puts i
puts i
end</lang>
end</syntaxhighlight>
This is syntactic sugar for:
This is syntactic sugar for:
<lang ruby>collection.each do |i|
<syntaxhighlight lang="ruby">collection.each do |i|
puts i
puts i
end</lang>
end</syntaxhighlight>
There are various flavours of <code>each</code> that may be class-dependent: [http://www.ruby-doc.org/core/classes/String.html#M000862 String#each_char], [http://www.ruby-doc.org/core/classes/Array.html#M002174 Array#each_index], [http://www.ruby-doc.org/core/classes/Hash.html#M002863 Hash#each_key], etc
There are various flavours of <code>each</code> that may be class-dependent: [http://www.ruby-doc.org/core/classes/String.html#M000862 String#each_char], [http://www.ruby-doc.org/core/classes/Array.html#M002174 Array#each_index], [http://www.ruby-doc.org/core/classes/Hash.html#M002863 Hash#each_key], etc


=={{header|Rust}}==
=={{header|Rust}}==
Rust's for-loop already is a foreach-loop.
Rust's for-loop already is a foreach-loop.
<lang rust>let collection = vec![1,2,3,4,5];
<syntaxhighlight lang="rust">let collection = vec![1,2,3,4,5];
for elem in collection {
for elem in collection {
println!("{}", elem);
println!("{}", elem);
}</lang>
}</syntaxhighlight>


Do note that Rust moves values by default and doesn't copy them. A vector would be unusable after looping over it like above. To preserve it, borrow it or use an Iter, to mutate values do a mutable borrow or create an IterMut. To get an immutable reference omit the mut-part.
Do note that Rust moves values by default and doesn't copy them. A vector would be unusable after looping over it like above. To preserve it, borrow it or use an Iter, to mutate values do a mutable borrow or create an IterMut. To get an immutable reference omit the mut-part.
<lang rust>let mut collection = vec![1,2,3,4,5];
<syntaxhighlight lang="rust">let mut collection = vec![1,2,3,4,5];
for mut_ref in &mut collection {
for mut_ref in &mut collection {
// alternatively:
// alternatively:
Line 2,403: Line 2,403:
// for immut_ref in collection.iter() {
// for immut_ref in collection.iter() {
println!("{}", *immut_ref);
println!("{}", *immut_ref);
}</lang>
}</syntaxhighlight>


Since Rust 1.21 foreach can be used explicitly executing a closure on each element.
Since Rust 1.21 foreach can be used explicitly executing a closure on each element.
<lang rust>let collection = vec![1, 2, 3, 4, 5];
<syntaxhighlight lang="rust">let collection = vec![1, 2, 3, 4, 5];
collection.iter().for_each(|elem| println!("{}", elem));</lang>
collection.iter().for_each(|elem| println!("{}", elem));</syntaxhighlight>


=={{header|Salmon}}==
=={{header|Salmon}}==
<lang Salmon>iterate (x; ["Red", "Green", "Blue"])
<syntaxhighlight lang="salmon">iterate (x; ["Red", "Green", "Blue"])
x!;</lang>
x!;</syntaxhighlight>
output:
output:
<pre>
<pre>
Line 2,420: Line 2,420:


=={{header|SAS}}==
=={{header|SAS}}==
<lang sas>/* Initialize an array with integers 1 to 10, and print their sum */
<syntaxhighlight lang="sas">/* Initialize an array with integers 1 to 10, and print their sum */
data _null_;
data _null_;
array a a1-a10;
array a a1-a10;
Line 2,430: Line 2,430:
s=sum(of a{*});
s=sum(of a{*});
put s;
put s;
run;</lang>
run;</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
main is
main is
num:ARRAY{INT} := |1, 5, 4, 3, 10|;
num:ARRAY{INT} := |1, 5, 4, 3, 10|;
Line 2,442: Line 2,442:
end;
end;
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>val collection = Array(1, 2, 3, 4)
<syntaxhighlight lang="scala">val collection = Array(1, 2, 3, 4)
collection.foreach(println)</lang>
collection.foreach(println)</syntaxhighlight>
Alternatively:
Alternatively:
<lang scala>(element <- 1 to 4).foreach(println)</lang>
<syntaxhighlight lang="scala">(element <- 1 to 4).foreach(println)</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
List:
List:
<lang scheme>(for-each
<syntaxhighlight lang="scheme">(for-each
(lambda (i) (display i) (newline))
(lambda (i) (display i) (newline))
the_list)</lang>
the_list)</syntaxhighlight>


=={{header|Scilab}}==
=={{header|Scilab}}==
{{works with|Scilab|5.5.1}}
{{works with|Scilab|5.5.1}}
<lang>for e=["a","b","c"]
<syntaxhighlight lang="text">for e=["a","b","c"]
printf("%s\n",e)
printf("%s\n",e)
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>a
<pre>a
Line 2,468: Line 2,468:
=={{header|Seed7}}==
=={{header|Seed7}}==
The for loop of Seed7 can be used to loop over the elements of a container.
The for loop of Seed7 can be used to loop over the elements of a container.
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


var array string: things is [] ("Apple", "Banana", "Coconut");
var array string: things is [] ("Apple", "Banana", "Coconut");
Line 2,479: Line 2,479:
writeln(thing);
writeln(thing);
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


=={{header|Self}}==
=={{header|Self}}==
<lang self>aCollection do: [| :element | element printLine ].</lang>
<syntaxhighlight lang="self">aCollection do: [| :element | element printLine ].</syntaxhighlight>
(Provided that the objects in the collection understand the <code>printLine</code> method).
(Provided that the objects in the collection understand the <code>printLine</code> method).


=={{header|SETL}}==
=={{header|SETL}}==
<lang setl>S := {1,2,3,5,8,13,21,34,55,89};
<syntaxhighlight lang="setl">S := {1,2,3,5,8,13,21,34,55,89};
for e in S loop
for e in S loop
print(e);
print(e);
end loop;</lang>
end loop;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
'''foreach''' loop:
'''foreach''' loop:
<lang ruby>foreach [1,2,3] { |i|
<syntaxhighlight lang="ruby">foreach [1,2,3] { |i|
say i
say i
}</lang>
}</syntaxhighlight>


'''for-in''' loop:
'''for-in''' loop:
<lang ruby>for i in [1,2,3] {
<syntaxhighlight lang="ruby">for i in [1,2,3] {
say i
say i
}</lang>
}</syntaxhighlight>


'''.each''' method:
'''.each''' method:
<lang ruby>[1,2,3].each { |i|
<syntaxhighlight lang="ruby">[1,2,3].each { |i|
say i
say i
}</lang>
}</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>c do: [| :obj | print: obj].</lang>
<syntaxhighlight lang="slate">c do: [| :obj | print: obj].</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>aCollection do: [ :element | element displayNl ].</lang>
<syntaxhighlight lang="smalltalk">aCollection do: [ :element | element displayNl ].</syntaxhighlight>
Provided that the objects in the collection understand the <code>displayNl</code> method (which can be added, if missing).
Provided that the objects in the collection understand the <code>displayNl</code> method (which can be added, if missing).


Most modern Smalltalks allow for a selector symbol to be sent a <tt>value:</tt> message; which allows for the very compact:
Most modern Smalltalks allow for a selector symbol to be sent a <tt>value:</tt> message; which allows for the very compact:
<lang smalltalk>aCollection do:#displayNl.</lang>
<syntaxhighlight lang="smalltalk">aCollection do:#displayNl.</syntaxhighlight>


(and because Aikido mentions it: of course this works for any kind of collection (and even things which simply implement a <tt>do:</tt> method to iterate on something)
(and because Aikido mentions it: of course this works for any kind of collection (and even things which simply implement a <tt>do:</tt> method to iterate on something)
<lang smalltalk>(1 to:6 by:2) do:#displayNl.
<syntaxhighlight lang="smalltalk">(1 to:6 by:2) do:#displayNl.
'hello' do:#displayNl.
'hello' do:#displayNl.
(Integer primesUpTo:100) do:#displayNl.
(Integer primesUpTo:100) do:#displayNl.
Line 2,530: Line 2,530:
arg value:'no classes needed'].
arg value:'no classes needed'].
funnyClassLessObject do:#displayNl.
funnyClassLessObject do:#displayNl.
etc.</lang>
etc.</syntaxhighlight>
{{out}}
{{out}}
1
1
Line 2,557: Line 2,557:
=={{header|Snabel}}==
=={{header|Snabel}}==
Prints foo, bar & baz followed by newlines.
Prints foo, bar & baz followed by newlines.
<lang snabel>['foo' 'bar' 'baz'] &say for</lang>
<syntaxhighlight lang="snabel">['foo' 'bar' 'baz'] &say for</syntaxhighlight>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
Line 2,563: Line 2,563:
Sparkling currently has no "foreach" construct, but there's a "foreach" function in the standard library:
Sparkling currently has no "foreach" construct, but there's a "foreach" function in the standard library:


<lang sparkling>let hash = { "foo": 42, "bar": 1337, "baz": "qux" };
<syntaxhighlight lang="sparkling">let hash = { "foo": 42, "bar": 1337, "baz": "qux" };
foreach(hash, function(key, val) {
foreach(hash, function(key, val) {
print(key, " -> ", val);
print(key, " -> ", val);
});</lang>
});</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
List of integers:
List of integers:
<lang sml>app
<syntaxhighlight lang="sml">app
(fn i => print (Int.toString i ^ "\n"))
(fn i => print (Int.toString i ^ "\n"))
collect_list</lang>
collect_list</syntaxhighlight>
Array of integers:
Array of integers:
<lang sml>Array.app
<syntaxhighlight lang="sml">Array.app
(fn i => print (Int.toString i ^ "\n"))
(fn i => print (Int.toString i ^ "\n"))
collect_array</lang>
collect_array</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>local a 2 9 4 7 5 3 6 1 8
<syntaxhighlight lang="stata">local a 2 9 4 7 5 3 6 1 8
foreach i in `a' {
foreach i in `a' {
display "`i'"
display "`i'"
}</lang>
}</syntaxhighlight>


=={{header|Suneido}}==
=={{header|Suneido}}==
<lang Suneido>for i in #(1, 2, 3)
<syntaxhighlight lang="suneido">for i in #(1, 2, 3)
Print(i)</lang>
Print(i)</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>for i in [1,2,3] {
<syntaxhighlight lang="swift">for i in [1,2,3] {
print(i)
print(i)
}</lang>
}</syntaxhighlight>
This works for any type that conforms to the <code>SequenceType</code> protocol (including arrays, collections, generators, ranges).
This works for any type that conforms to the <code>SequenceType</code> protocol (including arrays, collections, generators, ranges).


Alternately:
Alternately:
{{works with|Swift|2.x+}}
{{works with|Swift|2.x+}}
<lang swift>[1,2,3].forEach {
<syntaxhighlight lang="swift">[1,2,3].forEach {
print($0)
print($0)
}</lang>
}</syntaxhighlight>


=={{header|SystemVerilog}}==
=={{header|SystemVerilog}}==
<lang SystemVerilog>program main;
<syntaxhighlight lang="systemverilog">program main;
int values[$];
int values[$];


Line 2,610: Line 2,610:
end
end
end
end
endprogram</lang>
endprogram</syntaxhighlight>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
Stream them
Stream them
<lang tailspin>
<syntaxhighlight lang="tailspin">
['a', 'b', 'c'] ... -> !OUT::write
['a', 'b', 'c'] ... -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>abc</pre>
<pre>abc</pre>


Lists/arrays can be put through an array transform to get the index as well
Lists/arrays can be put through an array transform to get the index as well
<lang tailspin>
<syntaxhighlight lang="tailspin">
['a', 'b', 'c'] -> \[i]('$i;:$;
['a', 'b', 'c'] -> \[i]('$i;:$;
' -> !OUT::write \) -> !VOID
' -> !OUT::write \) -> !VOID
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,633: Line 2,633:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>foreach i {foo bar baz} {
<syntaxhighlight lang="tcl">foreach i {foo bar baz} {
puts "$i"
puts "$i"
}</lang>
}</syntaxhighlight>
Note that <tt>foreach</tt> also accepts multiple variables:
Note that <tt>foreach</tt> also accepts multiple variables:
<lang tcl>foreach {x y} {1 2 3 4} {
<syntaxhighlight lang="tcl">foreach {x y} {1 2 3 4} {
puts "$x,$y"
puts "$x,$y"
}</lang>
}</syntaxhighlight>
And also multiple lists:
And also multiple lists:
<lang tcl>foreach i {1 2 3} j {a b c} {
<syntaxhighlight lang="tcl">foreach i {1 2 3} j {a b c} {
puts "$i,$j"
puts "$i,$j"
}</lang>
}</syntaxhighlight>
Or any combination of variables/list:
Or any combination of variables/list:
<lang tcl>foreach i {1 2 3} {x y} {a b c d e f} {
<syntaxhighlight lang="tcl">foreach i {1 2 3} {x y} {a b c d e f} {
puts "$i,$x,$y"
puts "$i,$x,$y"
}</lang>
}</syntaxhighlight>


=={{header|Trith}}==
=={{header|Trith}}==
<lang trith>[1 2 3 4 5] [print] each</lang>
<syntaxhighlight lang="trith">[1 2 3 4 5] [print] each</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>$$ MODE TUSCRIPT
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
week="Monday'Tuesday'Wednesday'Thursday'Friday'Saterday'Sunday"
week="Monday'Tuesday'Wednesday'Thursday'Friday'Saterday'Sunday"
LOOP day=week
LOOP day=week
PRINT day
PRINT day
ENDLOOP</lang>
ENDLOOP</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,672: Line 2,672:
To iterate any single list, you use a <code>for</code> loop.
To iterate any single list, you use a <code>for</code> loop.
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>for file in *.sh; do
<syntaxhighlight lang="bash">for file in *.sh; do
echo "filename is $file"
echo "filename is $file"
done</lang>
done</syntaxhighlight>
If the list is in a shell parameter (like <code>PATH</code>), you adjust <code>IFS</code>.
If the list is in a shell parameter (like <code>PATH</code>), you adjust <code>IFS</code>.
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin
<syntaxhighlight lang="bash">PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin


oldifs=$IFS
oldifs=$IFS
Line 2,684: Line 2,684:
echo search $dir
echo search $dir
done
done
IFS=$oldifs</lang>
IFS=$oldifs</syntaxhighlight>
Some shells have real arrays. The <code>for</code> loop can also iterate these.
Some shells have real arrays. The <code>for</code> loop can also iterate these.
{{works with|Bash}}
{{works with|Bash}}
<lang bash>collection=("first" "second" "third" "fourth" "something else")
<syntaxhighlight lang="bash">collection=("first" "second" "third" "fourth" "something else")
for x in "${collection[@]}"; do
for x in "${collection[@]}"; do
echo "$x"
echo "$x"
done</lang>
done</syntaxhighlight>
{{works with|pdksh|5.2.14}}
{{works with|pdksh|5.2.14}}
<lang bash>set -A collection "first" "second" "third" "fourth" "something else"
<syntaxhighlight lang="bash">set -A collection "first" "second" "third" "fourth" "something else"
for x in "${collection[@]}"; do
for x in "${collection[@]}"; do
echo "$x"
echo "$x"
done</lang>
done</syntaxhighlight>


==={{header|C Shell}}===
==={{header|C Shell}}===
<lang csh>set collection=(first second third fourth "something else")
<syntaxhighlight lang="csh">set collection=(first second third fourth "something else")
foreach x ($collection:q)
foreach x ($collection:q)
echo $x:q
echo $x:q
end</lang>
end</syntaxhighlight>


=={{header|V}}==
=={{header|V}}==
<lang v>[1 2 3] [puts] step</lang>
<syntaxhighlight lang="v">[1 2 3] [puts] step</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>List<string> things = new List<string> ();
<syntaxhighlight lang="vala">List<string> things = new List<string> ();
things.append("Apple");
things.append("Apple");
things.append("Banana");
things.append("Banana");
Line 2,715: Line 2,715:
{
{
stdout.printf("%s\n", thing);
stdout.printf("%s\n", thing);
}</lang>
}</syntaxhighlight>


=={{header|Vim Script}}==
=={{header|Vim Script}}==
Vim Script's for-loop is actually a foreach-loop and iterates through a list.
Vim Script's for-loop is actually a foreach-loop and iterates through a list.
<lang vim>for i in ["alpha", "beta", 42, 5.54]
<syntaxhighlight lang="vim">for i in ["alpha", "beta", 42, 5.54]
echo i
echo i
endfor</lang>
endfor</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|go}}
{{trans|go}}


<lang vlang>fn print_all(values []int) {
<syntaxhighlight lang="vlang">fn print_all(values []int) {
for i, x in values {
for i, x in values {
println("Item $i = $x")
println("Item $i = $x")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Wart}}==
=={{header|Wart}}==
<lang wart>each x '(1 2 3)
<syntaxhighlight lang="wart">each x '(1 2 3)
prn x</lang>
prn x</syntaxhighlight>


=={{header|WDTE}}==
=={{header|WDTE}}==
<lang WDTE>let a => import 'arrays';
<syntaxhighlight lang="wdte">let a => import 'arrays';
let s => import 'stream';
let s => import 'stream';


Line 2,743: Line 2,743:
-> s.map (io.writeln io.stdout)
-> s.map (io.writeln io.stdout)
-> s.drain
-> s.drain
;</lang>
;</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>for (f in ["apples", "oranges", "pears"]) System.print(f)</lang>
<syntaxhighlight lang="ecmascript">for (f in ["apples", "oranges", "pears"]) System.print(f)</syntaxhighlight>


{{out}}
{{out}}
Line 2,757: Line 2,757:
=={{header|XLISP}}==
=={{header|XLISP}}==
XLISP's <tt>FOR-EACH</tt> applies a procedure to each member of a list in turn.
XLISP's <tt>FOR-EACH</tt> applies a procedure to each member of a list in turn.
<lang lisp>(FOR-EACH PRINT '(CYRUS CAMBYSES DARIUS XERXES ARTAXERXES))</lang>
<syntaxhighlight lang="lisp">(FOR-EACH PRINT '(CYRUS CAMBYSES DARIUS XERXES ARTAXERXES))</syntaxhighlight>
{{out}}
{{out}}
<pre>CYRUS
<pre>CYRUS
Line 2,767: Line 2,767:
=={{header|XPL0}}==
=={{header|XPL0}}==
Translation of C example:
Translation of C example:
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int List, I;
int List, I;
[List:= ["Red", "Green", "Blue", "Black", "White"];
[List:= ["Red", "Green", "Blue", "Black", "White"];
for I:= 0, 5-1 do
for I:= 0, 5-1 do
[Text(0, List(I)); CrLf(0)];
[Text(0, List(I)); CrLf(0)];
]</lang>
]</syntaxhighlight>


=={{header|XSLT}}==
=={{header|XSLT}}==
For-each is the only iteration construct that is built into XSLT. All other iteration is either implied by applying a template to all members matching an XPath expression, or built from recursive application of a template. You have access to something like a loop counter with the one-based "position()" function.
For-each is the only iteration construct that is built into XSLT. All other iteration is either implied by applying a template to all members matching an XPath expression, or built from recursive application of a template. You have access to something like a loop counter with the one-based "position()" function.
<lang xml><fo:block font-weight="bold">Adults:</fo:block>
<syntaxhighlight lang="xml"><fo:block font-weight="bold">Adults:</fo:block>
<xsl:for-each select="person[@age &gt;= 21]">
<xsl:for-each select="person[@age &gt;= 21]">
<fo:block><xsl:value-of select="position()"/>. <xsl:value-of select="@name"/></fo:block>
<fo:block><xsl:value-of select="position()"/>. <xsl:value-of select="@name"/></fo:block>
</xsl:for-each></lang>
</xsl:for-each></syntaxhighlight>


=={{header|zig}}==
=={{header|zig}}==
<lang zig>const warn = @import("std").debug.warn;
<syntaxhighlight lang="zig">const warn = @import("std").debug.warn;
pub fn main() void {
pub fn main() void {
Line 2,791: Line 2,791:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|zkl}}==
=={{header|zkl}}==
{{trans|XPL0}}
{{trans|XPL0}}
<lang zkl>foreach c in (T("Red","Green","Blue","Black","White"))
<syntaxhighlight lang="zkl">foreach c in (T("Red","Green","Blue","Black","White"))
{ print(c," "); }</lang>
{ print(c," "); }</syntaxhighlight>
{{out}}
{{out}}
<pre>Red Green Blue Black White</pre>
<pre>Red Green Blue Black White</pre>
Other forms of foreach, one that breaks apart a container into elements and one line nested loops.
Other forms of foreach, one that breaks apart a container into elements and one line nested loops.
<lang zkl>foreach x,y,z in (T(T(1,2,3), T(4,5,6))) { println(x,y,z) }
<syntaxhighlight lang="zkl">foreach x,y,z in (T(T(1,2,3), T(4,5,6))) { println(x,y,z) }
foreach x,y,z in (T(1,2,3), T(4,5), T(6)){ println(x,y,z) }</lang>
foreach x,y,z in (T(1,2,3), T(4,5), T(6)){ println(x,y,z) }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,817: Line 2,817:


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");


pub fn main() !void {
pub fn main() !void {
Line 2,831: Line 2,831:
// Convention is to provide a `next()` method.
// Convention is to provide a `next()` method.
// TODO
// TODO
}</lang>
}</syntaxhighlight>


{{omit from|GUISS}}
{{omit from|GUISS}}