Loops/Foreach: Difference between revisions
m added a related task. |
Add ed example |
||
(116 intermediate revisions by 65 users not shown) | |||
Line 22: | Line 22: | ||
* [[Loops/Wrong ranges]] |
* [[Loops/Wrong ranges]] |
||
<br><br> |
<br><br> |
||
=={{header|11l}}== |
|||
{{trans|C#}} |
|||
<syntaxhighlight lang="11l">V things = [‘Apple’, ‘Banana’, ‘Coconut’] |
|||
L(thing) things |
|||
print(thing)</syntaxhighlight> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<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)))))</ |
(print-list (rest xs)))))</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 39: | Line 47: | ||
SYM |
SYM |
||
NIL |
NIL |
||
</pre> |
|||
=={{header|Action!}}== |
|||
In Action! there is no for-each loop. |
|||
<syntaxhighlight lang="action!">PROC Main() |
|||
DEFINE PTR="CARD" |
|||
BYTE i |
|||
PTR ARRAY items(10) |
|||
items(0)="First" items(1)="Second" |
|||
items(2)="Third" items(3)="Fourth" |
|||
items(4)="Fifth" items(5)="Sixth" |
|||
items(6)="Seventh" items(7)="Eighth" |
|||
items(8)="Ninth" items(9)="Tenth" |
|||
PrintE("In Action! there is no for-each loop") |
|||
PutE() |
|||
FOR i=0 TO 9 |
|||
DO |
|||
PrintE(items(i)) |
|||
OD |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Foreach.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
In Action! there is no for-each loop |
|||
First |
|||
Second |
|||
Third |
|||
Fourth |
|||
Fifth |
|||
Sixth |
|||
Seventh |
|||
Eighth |
|||
Ninth |
|||
Tenth |
|||
</pre> |
</pre> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
===arrays=== |
===arrays=== |
||
< |
<syntaxhighlight lang="ada">with Ada.Integer_Text_IO; |
||
use Ada.Integer_Text_IO; |
use Ada.Integer_Text_IO; |
||
Line 56: | Line 100: | ||
end loop; |
end loop; |
||
end For_Each;</ |
end For_Each;</syntaxhighlight> |
||
Alternative solution (Ada 2012): |
Alternative solution (Ada 2012): |
||
< |
<syntaxhighlight lang="ada"> for Item of A loop |
||
Put( Item ); |
Put( Item ); |
||
end loop;</ |
end loop;</syntaxhighlight> |
||
===doubly linked lists=== |
===doubly linked lists=== |
||
{{works with|Ada 2005}} |
{{works with|Ada 2005}} |
||
< |
<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 90: | Line 134: | ||
DL_List.Iterate (Print_Node'Access); |
DL_List.Iterate (Print_Node'Access); |
||
end Doubly_Linked_List;</ |
end Doubly_Linked_List;</syntaxhighlight> |
||
===vectors=== |
===vectors=== |
||
{{works with|Ada 2005}} |
{{works with|Ada 2005}} |
||
< |
<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 117: | Line 161: | ||
V.Iterate (Print_Element'Access); |
V.Iterate (Print_Element'Access); |
||
end Vector_Example;</ |
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=== |
||
< |
<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 |
||
}</ |
}</syntaxhighlight> |
||
===vectors=== |
===vectors=== |
||
< |
<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) |
||
}</ |
}</syntaxhighlight> |
||
===maps=== |
===maps=== |
||
< |
<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) |
||
}</ |
}</syntaxhighlight> |
||
===integers=== |
===integers=== |
||
< |
<syntaxhighlight lang="aikido">foreach i 100 { |
||
println (i) // prints values 0..99 |
println (i) // prints values 0..99 |
||
} |
} |
||
Line 149: | 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) |
||
}</ |
}</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 |
||
< |
<syntaxhighlight lang="aikido">class List { |
||
class Element (public data) { |
class Element (public data) { |
||
public var next = null |
public var next = null |
||
Line 185: | Line 229: | ||
foreach n list { |
foreach n list { |
||
println (n) |
println (n) |
||
}</ |
}</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. |
||
< |
<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 200: | Line 244: | ||
foreach s squares (start, end) { |
foreach s squares (start, end) { |
||
println (s) |
println (s) |
||
}</ |
}</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 |
||
< |
<syntaxhighlight lang="aikido">var s = openin ("input.txt") |
||
foreach line s { |
foreach line s { |
||
print (line) |
print (line) |
||
}</ |
}</syntaxhighlight> |
||
===Enumerations=== |
===Enumerations=== |
||
< |
<syntaxhighlight lang="aikido">enum Color { |
||
RED, GREEN, BLUE |
RED, GREEN, BLUE |
||
} |
} |
||
Line 214: | Line 258: | ||
foreach color Color { |
foreach color Color { |
||
println (color) |
println (color) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<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)) { |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 228: | 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}} |
||
< |
<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</ |
OD</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Mary Had +1 little lamb. |
Mary Had +1 little lamb. |
||
</pre> |
</pre> |
||
<br> |
|||
Note: [[ALGOL 68S]] actually has a reserved word FOREACH that is used to break arrays in to portions, and process in parallel. |
|||
[[ALGOL 68S]] has a reserved word FOREACH that is used to break arrays in to portions, and process in parallel. |
|||
<br> |
|||
<br>[[ALGOL 68RS]] and [[Algol68toc]] have a FORALL loop, the following is equivalent to the example above: |
|||
<syntaxhighlight lang="algol68">FORALL c IN collection DO |
|||
print((c," ")) |
|||
OD</syntaxhighlight> |
|||
=={{header|Amazing Hopper}}== |
|||
<syntaxhighlight lang="c"> |
|||
#include <jambo.h> |
|||
Main |
|||
things = {}, len list=0 |
|||
Set ' 100,200,300,"Hello world!", -3,-2,-1 ' Apndlist 'things' |
|||
Let ' len list := Length(things) ' |
|||
Printnl ' "\nNormal count:\n" ' |
|||
For each( n, things, len list ) |
|||
Printnl ' "Thing : ", n ' |
|||
Next |
|||
Printnl ' "\n\nReverse count:\n" ' |
|||
For each reverse ( n, things, len list ) |
|||
Printnl ' "Thing : ", n ' |
|||
Next |
|||
End |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Normal count: |
|||
Thing : 100 |
|||
Thing : 200 |
|||
Thing : 300 |
|||
Thing : Hello world! |
|||
Thing : -3 |
|||
Thing : -2 |
|||
Thing : -1 |
|||
Reverse count: |
|||
Thing : -1 |
|||
Thing : -2 |
|||
Thing : -3 |
|||
Thing : Hello world! |
|||
Thing : 300 |
|||
Thing : 200 |
|||
Thing : 100 |
|||
</pre> |
|||
=={{header|AmigaE}}== |
=={{header|AmigaE}}== |
||
< |
<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 248: | Line 342: | ||
-> 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</ |
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 257: | Line 351: | ||
System.debug(i); |
System.debug(i); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">repeat with fruit in {"Apple", "Orange", "Banana"} |
||
log contents of fruit |
log contents of fruit |
||
end repeat</ |
end repeat</syntaxhighlight> |
||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">arr: ["one" "two" "three"] |
|||
dict: #[ |
|||
name: "John" |
|||
surname: "Doe" |
|||
age: 34 |
|||
] |
|||
loop arr 'item -> |
|||
print item |
|||
loop dict [key val]-> |
|||
print [key "=>" val]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>one |
|||
two |
|||
three |
|||
name => John |
|||
surname => Doe |
|||
age => 34</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">string = mary,had,a,little,lamb |
||
Loop, Parse, string, `, |
Loop, Parse, string, `, |
||
MsgBox %A_LoopField%</ |
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). |
||
< |
<syntaxhighlight lang="awk"> |
||
BEGIN { |
BEGIN { |
||
split("Mary had a little lamb", strs, " ") |
split("Mary had a little lamb", strs, " ") |
||
Line 277: | Line 393: | ||
print strs[el] |
print strs[el] |
||
} |
} |
||
}</ |
}</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 283: | Line 399: | ||
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: |
||
< |
<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] |
||
} |
} |
||
}</ |
}</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: |
||
< |
<syntaxhighlight lang="awk"># This will not work |
||
BEGIN { |
BEGIN { |
||
for ( |
for (el in "apples","bananas","cherries") { |
||
print "I like " |
print "I like " el |
||
} |
|||
}</lang> |
|||
}</syntaxhighlight> |
|||
=={{header|Bait}}== |
|||
`for-in` loops work with both builtin container types (arrays and maps). |
|||
They allow to iterate the indices/keys and values. |
|||
<syntaxhighlight lang="bait"> |
|||
fun for_in_array() { |
|||
arr := ['1st', '2nd', '3rd'] |
|||
// Iterate over array indices and elements |
|||
for i, val in arr { |
|||
println('${i}: ${val}') |
|||
} |
|||
// Using only one variable will iterate over the elements |
|||
for val in arr { |
|||
println(val) |
|||
} |
|||
// To only iterate over the indices, use `_` as the second variable name. |
|||
// `_` is a special variable that will ignore any assigned value |
|||
for i, _ in arr { |
|||
println(i) |
|||
} |
|||
} |
|||
fun for_in_map() { |
|||
nato_abc := map{ |
|||
'a': 'Alpha' |
|||
'b': 'Bravo' |
|||
'c': 'Charlie' |
|||
'd': 'Delta' |
|||
} |
|||
// Iterate over map keys and values. |
|||
// Note that, unlike arrays, only the two-variable variant is allowed |
|||
for key, val in nato_abc { |
|||
println('${key}: ${val}') |
|||
} |
|||
} |
|||
fun main() { |
|||
for_in_array() |
|||
println('') |
|||
for_in_map() |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
==={{header|BaCon}}=== |
|||
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. |
|||
<syntaxhighlight lang="freebasic">OPTION COLLAPSE TRUE |
|||
FOR x$ IN "Hello cruel world" |
|||
PRINT x$ |
|||
NEXT |
|||
FOR y$ IN "1,2,\"3,4\",5" STEP "," |
|||
PRINT y$ |
|||
NEXT</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ bacon -q forin.bac >/dev/null |
|||
prompt$ ./forin |
|||
Hello |
|||
cruel |
|||
world |
|||
1 |
|||
2 |
|||
"3,4" |
|||
5</pre> |
|||
The <code>OPTION COLLAPSE TRUE</code> statements prevents empty results when multiple delimiters appear together. The default delimiter is space, and can be changed with <code>OPTION DELIM x</code> where x is a static string literal. |
|||
==={{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. |
||
< |
<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 309: | Line 498: | ||
PRINT collection$[i]+ " "; |
PRINT collection$[i]+ " "; |
||
NEXT i |
NEXT i |
||
PRINT</ |
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 315: | Line 504: | ||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<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 322: | Line 511: | ||
PRINT collection$(index%) " "; |
PRINT collection$(index%) " "; |
||
NEXT |
NEXT |
||
PRINT</ |
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 |
||
< |
<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 336: | Line 525: | ||
90 NEXT |
90 NEXT |
||
100 END |
100 END |
||
1000 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</ |
1000 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</syntaxhighlight> |
||
==={{header|Creative Basic}}=== |
==={{header|Creative Basic}}=== |
||
< |
<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 358: | Line 547: | ||
'because this is a console only program. |
'because this is a console only program. |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|FreeBASIC}}=== |
==={{header|FreeBASIC}}=== |
||
< |
<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 378: | Line 567: | ||
Print |
Print |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 384: | Line 573: | ||
1 2 3 4 5 6 7 8 9 10 11 |
1 2 3 4 5 6 7 8 9 10 11 |
||
</pre> |
</pre> |
||
==={{header|Gambas}}=== |
|||
'''[https://gambas-playground.proko.eu/?gist=cb94500c68749f6f93915f3f10de5a03 Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Dim siInput As Short[] = [1, 8, 0, 6, 4, 7, 3, 2, 5, 9] |
|||
Dim siTemp As Short |
|||
For Each siTemp In siInput.Sort() |
|||
Print siTemp;; |
|||
Next |
|||
End</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0 1 2 3 4 5 6 7 8 9 |
|||
</pre> |
|||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 STRING COLLECTION$(1 TO 9)*8 |
|||
110 LET I=1 |
|||
120 DO |
|||
130 READ IF MISSING EXIT DO:COLLECTION$(I) |
|||
140 LET I=I+1 |
|||
150 LOOP |
|||
160 FOR J=1 TO I-1 |
|||
170 PRINT COLLECTION$(J);" "; |
|||
180 NEXT |
|||
190 DATA The,quick,brown,fox,jumps,over,the,lazy,dog.</syntaxhighlight> |
|||
==={{header|IWBASIC}}=== |
==={{header|IWBASIC}}=== |
||
'''Linked List''' |
'''Linked List''' |
||
< |
<syntaxhighlight lang="iwbasic">DEF AList:POINTER |
||
AList=ListCreate() |
AList=ListCreate() |
||
Line 418: | Line 635: | ||
'Because this is a console only program. |
'Because this is a console only program. |
||
END</ |
END</syntaxhighlight> |
||
'''An Array''' |
'''An Array''' |
||
< |
<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 438: | Line 655: | ||
'Because this is a console only program. |
'Because this is a console only program. |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|Lambdatalk}}=== |
|||
<syntaxhighlight lang="scheme"> |
|||
{def collection alpha beta gamma delta} |
|||
-> collection |
|||
{S.map {lambda {:i} {br}:i} {collection}} |
|||
-> |
|||
alpha |
|||
beta |
|||
gamma |
|||
delta |
|||
or |
|||
{def S.foreach |
|||
{lambda {:s} |
|||
{if {S.empty? {S.rest :s}} |
|||
then {S.first :s} |
|||
else {S.first :s} {br}{S.foreach {S.rest :s}}}}} |
|||
{S.foreach {collection}} |
|||
-> |
|||
alpha |
|||
beta |
|||
gamma |
|||
delta |
|||
</syntaxhighlight> |
|||
==={{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. |
||
< |
<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 453: | Line 699: | ||
loop until 1 =2 |
loop until 1 =2 |
||
end</ |
end</syntaxhighlight> |
||
Not good! |
Not good! |
||
Hardly good! |
Hardly good! |
||
Line 462: | Line 708: | ||
Very good! |
Very good! |
||
Fantastically good! |
Fantastically good! |
||
==={{header|NS-HUBASIC}}=== |
|||
<syntaxhighlight lang="ns-hubasic">10 DIM A$(9) : REM DECLARE STRING ARRAY |
|||
20 REM ADD DATA TO ARRAY AND PRINT ARRAY CONTENTS |
|||
30 FOR I=0 TO 8 |
|||
40 READ A$(I) |
|||
50 PRINT A$(I)" "; |
|||
60 NEXT |
|||
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 |
||
< |
<syntaxhighlight lang="purebasic">ForEach element() |
||
PrintN(element()) |
PrintN(element()) |
||
Next</ |
Next</syntaxhighlight> |
||
==={{header|Run BASIC}}=== |
==={{header|Run BASIC}}=== |
||
< |
<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</ |
wend</syntaxhighlight> |
||
==={{header|TI-89 BASIC}}=== |
==={{header|TI-89 BASIC}}=== |
||
< |
<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</ |
EndFor</syntaxhighlight> |
||
==={{header|VBA}}=== |
|||
<syntaxhighlight lang="vb">Public Sub LoopsForeach() |
|||
Dim FruitArray() As Variant |
|||
Dim Fruit As Variant |
|||
FruitArray = [{"Apple","Banana","Strawberry"}] |
|||
Dim FruitBasket As Collection |
|||
Set FruitBasket = New Collection |
|||
For Each Fruit In FruitArray |
|||
FruitBasket.Add Fruit |
|||
Next Fruit |
|||
For Each Fruit In FruitBasket |
|||
Debug.Print Fruit |
|||
Next Fruit |
|||
End Sub</syntaxhighlight> |
|||
==={{header|VBScript}}=== |
|||
<syntaxhighlight lang="vbscript">items = Array("Apple", "Orange", "Banana") |
|||
For Each x In items |
|||
WScript.Echo x |
|||
Next</syntaxhighlight> |
|||
==={{header|Visual Basic .NET}}=== |
==={{header|Visual Basic .NET}}=== |
||
< |
<syntaxhighlight lang="vbnet">Dim list As New List(Of String) |
||
list.Add("Car") |
list.Add("Car") |
||
list.Add("Boat") |
list.Add("Boat") |
||
Line 492: | Line 769: | ||
For Each item In list |
For Each item In list |
||
Console.WriteLine(item) |
Console.WriteLine(item) |
||
Next</ |
Next</syntaxhighlight> |
||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="yabasic">//Yabasic tampoco tiene una construcción ForEach. |
|||
//Mediante un bucle FOR iteramos a través de una matriz por índice. |
|||
//READ-DATA se usa para rellenar la matriz |
|||
dim arreglo(10) |
|||
data 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 |
|||
for each = 0 to arraysize(a(),1) |
|||
read arreglo(each) |
|||
next each |
|||
for each = 0 to arraysize(a(),1) |
|||
print arreglo(each), " "; |
|||
next each |
|||
print |
|||
end</syntaxhighlight> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
Line 498: | Line 794: | ||
'''Direct usage:''' |
'''Direct usage:''' |
||
< |
<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 |
||
)</ |
)</syntaxhighlight> |
||
'''Using a Collection Variable:''' |
'''Using a Collection Variable:''' |
||
< |
<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 |
||
)</ |
)</syntaxhighlight> |
||
{{Out|They have the Same Output}} |
{{Out|They have the Same Output}} |
||
<pre>This |
<pre>This |
||
Line 517: | Line 813: | ||
=={{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. |
||
< |
<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] |
||
}</ |
}</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: |
||
< |
<syntaxhighlight lang="bracmat"> ( list |
||
= Afrikaans |
= Afrikaans |
||
Ελληνικά |
Ελληνικά |
||
Line 533: | Line 829: | ||
മലയാളം |
മലയാളം |
||
ئۇيغۇرچە |
ئۇيغۇرچە |
||
)</ |
)</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: |
||
< |
<syntaxhighlight lang="bracmat"> !list:?L |
||
& whl'(!L:%?language ?L&out$!language)</ |
& 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. |
||
< |
<syntaxhighlight lang="bracmat"> !list:?L |
||
& ( loop |
& ( loop |
||
= !L:%?language ?L |
= !L:%?language ?L |
||
Line 544: | Line 840: | ||
& !loop |
& !loop |
||
) |
) |
||
& ~!loop</ |
& ~!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. |
||
< |
<syntaxhighlight lang="bracmat"> ( !list |
||
: ? (%@?language&out$!language&~) ? |
: ? (%@?language&out$!language&~) ? |
||
| |
| |
||
)</ |
)</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. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
... |
... |
||
Line 562: | Line 858: | ||
for(ix=0; ix<LIST_SIZE; ix++) { |
for(ix=0; ix<LIST_SIZE; ix++) { |
||
printf("%s\n", list[ix]); |
printf("%s\n", list[ix]); |
||
}</ |
}</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 585: | Line 881: | ||
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 605: | Line 901: | ||
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[0])] 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[0])] 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 634: | Line 930: | ||
return(0); |
return(0); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C sharp|C#}}== |
|||
<syntaxhighlight lang="csharp">string[] things = {"Apple", "Banana", "Coconut"}; |
|||
foreach (string thing in things) |
|||
{ |
|||
Console.WriteLine(thing); |
|||
}</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. |
||
< |
<syntaxhighlight lang="cpp">for (container_type::iterator i = container.begin(); i != container.end(); ++i) |
||
{ |
{ |
||
std::cout << *i << "\n"; |
std::cout << *i << "\n"; |
||
}</ |
}</syntaxhighlight> |
||
However the idiomatic way to output a container would be |
However the idiomatic way to output a container would be |
||
< |
<syntaxhighlight lang="cpp">std::copy(container.begin(), container.end(), |
||
std::ostream_iterator<container_type::value_type>(std::cout, "\n"));</ |
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. |
||
< |
<syntaxhighlight lang="cpp">void print_element(container_type::value_type const& v) |
||
{ |
{ |
||
std::cout << v << "\n"; |
std::cout << v << "\n"; |
||
Line 652: | Line 956: | ||
... |
... |
||
std::for_each(container.begin(), container.end(), print_element);</ |
std::for_each(container.begin(), container.end(), print_element);</syntaxhighlight> |
||
{{works with|C++11}} |
{{works with|C++11}} |
||
< |
<syntaxhighlight lang="cpp">for (auto element: container) |
||
{ |
{ |
||
std::cout << element << "\n"; |
std::cout << element << "\n"; |
||
}</ |
}</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: |
||
< |
<syntaxhighlight lang="cpp">for (auto const& element: container) |
||
{ |
{ |
||
std::cout << element << "\n"; |
std::cout << element << "\n"; |
||
}</ |
}</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): |
||
< |
<syntaxhighlight lang="cpp">for (auto&& element: container) //use a 'universal reference' |
||
{ |
{ |
||
element += 42; |
element += 42; |
||
}</ |
}</syntaxhighlight> |
||
=={{header| |
=={{header|C3}}== |
||
C3 has a standard built-in foreach for iterating through lists. |
|||
<lang csharp>string[] things = {"Apple", "Banana", "Coconut"}; |
|||
<syntaxhighlight lang="c3">String[] fruits = { "Apple", "Banana", "Strawberry" }; |
|||
foreach (string thing in things) |
|||
foreach (fruit : fruits) io::printn(fruit);</syntaxhighlight> |
|||
{ |
|||
Console.WriteLine(thing); |
|||
}</lang> |
|||
=={{header|Chapel}}== |
=={{header|Chapel}}== |
||
< |
<syntaxhighlight lang="chapel">var food = ["Milk", "Bread", "Butter"]; |
||
for f in food do writeln(f);</ |
for f in food do writeln(f);</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp">(doseq [item collection] (println item))</syntaxhighlight> |
||
=={{header|CLU}}== |
|||
As in Python (which no doubt got the idea from CLU), every <em>for</em> loop in |
|||
CLU is really a <em>foreach</em>, and iterating over a range of numbers is done |
|||
by using an iterator (e.g. <code>int$from_to</code>). |
|||
Unlike Python, the <em>for</em> loop '''only''' accepts iterators, and collections |
|||
are not automatically cast into iterators. To loop over the elements of an array, |
|||
one needs to explicitly use the <code>elements</code> iterator. |
|||
<syntaxhighlight lang="clu">start_up = proc () |
|||
po: stream := stream$primary_output() |
|||
words: array[string] := array[string]$ |
|||
["enemy", "lasagna", "robust", "below", "wax"] |
|||
for word: string in array[string]$elements(words) do |
|||
stream$putl(po, word) |
|||
end |
|||
end start_up</syntaxhighlight> |
|||
=={{header|CMake}}== |
=={{header|CMake}}== |
||
< |
<syntaxhighlight lang="cmake">set(list one.c two.c three.c) |
||
foreach(file ${list}) |
foreach(file ${list}) |
||
message(${file}) |
message(${file}) |
||
endforeach(file)</ |
endforeach(file)</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Line 695: | Line 1,018: | ||
{{trans|C#}} |
{{trans|C#}} |
||
{{works with|Visual COBOL}} |
{{works with|Visual COBOL}} |
||
< |
<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</ |
end-perform</syntaxhighlight> |
||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<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}}== |
||
< |
<syntaxhighlight lang="lisp">(loop for i in list do (print i))</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="lisp">(map nil #'print list)</syntaxhighlight> |
||
or |
|||
<syntaxhighlight lang="lisp">(dolist (x the-list) (print x))</syntaxhighlight> |
|||
or |
|||
<syntaxhighlight lang="lisp">(use-package :iterate) |
|||
(iter |
|||
(for x in the-list) |
|||
(print x))</syntaxhighlight> |
|||
=== Using DO === |
|||
<syntaxhighlight lang="lisp"> |
|||
(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 |
|||
((null i)) ; Break condition |
|||
(print (first i)))) ; On every loop print list's first element |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
7 |
|||
"foo" |
|||
1 |
|||
4 |
|||
</pre> |
|||
=={{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. |
||
< |
<syntaxhighlight lang="d">import std.stdio: writeln; |
||
void main() { |
void main() { |
||
Line 734: | Line 1,080: | ||
foreach (key, value; collection3) |
foreach (key, value; collection3) |
||
writeln(key, " ", value); |
writeln(key, " ", value); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>A |
<pre>A |
||
Line 750: | Line 1,096: | ||
=={{header|Dao}}== |
=={{header|Dao}}== |
||
< |
<syntaxhighlight lang="dao">items = { 1, 2, 3 } |
||
for( item in items ) io.writeln( item )</ |
for( item in items ) io.writeln( item )</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Line 757: | Line 1,103: | ||
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(). |
||
< |
<syntaxhighlight lang="delphi">program LoopForEach; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 766: | Line 1,112: | ||
for s in 'Hello' do |
for s in 'Hello' do |
||
Writeln(s); |
Writeln(s); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>H |
<pre>H |
||
Line 773: | Line 1,119: | ||
l |
l |
||
o</pre> |
o</pre> |
||
=={{header|Dragon}}== |
|||
<syntaxhighlight lang="dragon"> |
|||
for value : array { |
|||
showln value |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Dyalect}}== |
|||
<syntaxhighlight lang="dyalect">for i in [1,2,3] { |
|||
print(i) |
|||
}</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: |
|||
<syntaxhighlight lang="dyalect">for i in [1,2,3].Iterate() { |
|||
print(i) |
|||
}</syntaxhighlight> |
|||
This would perfectly work with any custom iterator as well: |
|||
<syntaxhighlight lang="dyalect">func myCollection() { |
|||
yield 1 |
|||
yield 2 |
|||
yield 3 |
|||
} |
|||
for i in myCollection() { |
|||
print(i) |
|||
}</syntaxhighlight> |
|||
All three code samples would output: |
|||
<pre>1 |
|||
2 |
|||
3</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">for e in theCollection { |
||
println(e) |
println(e) |
||
}</ |
}</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|EasyLang}}== |
|||
<syntaxhighlight lang="easylang"> |
|||
for i in [ 5 1 19 25 12 1 14 7 ] |
|||
print i |
|||
. |
|||
</syntaxhighlight> |
|||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<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 795: | Line 1,184: | ||
;; etc ... for other collections like Streams, Hashes, Graphs, ... |
;; etc ... for other collections like Streams, Hashes, Graphs, ... |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ecstasy}}== |
|||
<syntaxhighlight lang="java"> |
|||
module LoopForEach { |
|||
@Inject Console console; |
|||
void run() { |
|||
val vals = [10, 20, 30, 40]; |
|||
console.print("Array of values:"); |
|||
Loop: for (val val : vals) { |
|||
console.print($" value #{Loop.count + 1}: {val}"); |
|||
} |
|||
Map<String, Int> pairs = ["x"=42, "y"=69]; |
|||
console.print("\nKeys and values:"); |
|||
for ((String key, Int val) : pairs) { |
|||
console.print($" {key}={val}"); |
|||
} |
|||
console.print("\nJust the keys:"); |
|||
Loop: for (String key : pairs) { |
|||
console.print($" key #{Loop.count + 1}: {key}"); |
|||
} |
|||
console.print("\nValues from a range:"); |
|||
for (Int n : 1..5) { |
|||
console.print($" {n}"); |
|||
} |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Array of values: |
|||
value #1: 10 |
|||
value #2: 20 |
|||
value #3: 30 |
|||
value #4: 40 |
|||
Keys and values: |
|||
x=42 |
|||
y=69 |
|||
Just the keys: |
|||
key #1: x |
|||
key #2: y |
|||
Values from a range: |
|||
1 |
|||
2 |
|||
3 |
|||
4 |
|||
5 |
|||
</pre> |
|||
=={{header|Ed}}== |
|||
Print all (newline-separated) lines in the file. |
|||
<syntaxhighlight lang="sed"> |
|||
,p |
|||
</syntaxhighlight> |
|||
=={{header|Efene}}== |
=={{header|Efene}}== |
||
Any data structure can be printed as a whole, preformated: |
Any data structure can be printed as a whole, preformated: |
||
< |
<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. |
||
< |
<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>. |
||
< |
<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 812: | Line 1,262: | ||
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: |
||
< |
<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: |
||
< |
<syntaxhighlight lang="eiffel"> across my_list as ic some ic.item.count > 3 end</syntaxhighlight> |
||
=={{header|Ela}}== |
=={{header|Ela}}== |
||
< |
<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</ |
each xs</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA |
ELENA 6.x : |
||
< |
<syntaxhighlight lang="elena">import system'routines; |
||
import extensions |
import extensions; |
||
public program |
public program() |
||
{ |
|||
[ |
|||
var things := |
var things := new string[]{"Apple", "Banana", "Coconut"}; |
||
things |
things.forEach::(thing) |
||
{ |
|||
console |
console.printLine(thing) |
||
} |
|||
}</syntaxhighlight> |
|||
]</lang> |
|||
=== Using foreach statement template === |
|||
<syntaxhighlight lang="elena">import extensions; |
|||
public program() |
|||
{ |
|||
var things := new string[]{"Apple", "Banana", "Coconut"}; |
|||
foreach(var thing; in things) |
|||
{ |
|||
console.printLine(thing) |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<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 848: | Line 1,311: | ||
[3] |
[3] |
||
{0, 5} |
{0, 5} |
||
:ok</ |
:ok</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
For a list either <code>dolist</code> macro |
For a list either <code>dolist</code> macro |
||
< |
<syntaxhighlight lang="lisp">(dolist (x '(1 2 3 4)) |
||
(message "x=%d" x))</ |
(message "x=%d" x))</syntaxhighlight> |
||
or <code>mapc</code> function |
or <code>mapc</code> function |
||
< |
<syntaxhighlight lang="lisp">(mapc (lambda (x) |
||
(message "x=%d" x)) |
(message "x=%d" x)) |
||
'(1 2 3 4))</ |
'(1 2 3 4))</syntaxhighlight> |
||
<code>dolist</code> and <code>mapc</code> are both builtin in current Emacs. For past Emacs both can be had from <code>cl.el</code> with for instance <code>(eval-when-compile (require 'cl))</code>. |
|||
{{libheader|cl-lib}} |
|||
<code>cl.el</code> also offers a <code>loop</code> macro similar in style to [[#Common Lisp|Common Lisp]]. |
|||
<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: |
||
< |
<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. |
||
< |
<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. |
||
< |
<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> |
|||
include std/console.e |
include std/console.e |
||
Line 910: | Line 1,371: | ||
if getc(0) then end if |
if getc(0) then end if |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 948: | Line 1,409: | ||
2 |
2 |
||
</pre> |
</pre> |
||
=={{header|F_Sharp|F#}}== |
|||
We can use ''for'' directly or list iteration. |
|||
<syntaxhighlight lang="fsharp">for i in [1 .. 10] do printfn "%d" i |
|||
List.iter (fun i -> printfn "%d" i) [1 .. 10]</syntaxhighlight> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<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>. |
||
< |
<syntaxhighlight lang="fantom">class Main |
||
{ |
{ |
||
public static Void main () |
public static Void main () |
||
Line 964: | Line 1,431: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header| |
=={{header|Fennel}}== |
||
====sequential table==== |
|||
Unlike, bash or csh, the PATH variable is automatically converted to real array. |
|||
<syntaxhighlight lang="fennel">(each [k v (ipairs [:apple :banana :orange])] |
|||
<lang fishshell>for path in $PATH |
|||
(print k v))</syntaxhighlight> |
|||
echo You have $path in PATH. |
|||
{{out}} |
|||
end</lang> |
|||
<pre>1 apple |
|||
2 banana |
|||
3 orange</pre> |
|||
====key-value table==== |
|||
<syntaxhighlight lang="fennel">(each [k v (pairs {:apple :x :banana 4 :orange 3})] |
|||
(print k v))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>apple x |
|||
banana 4 |
|||
orange 3</pre> |
|||
=={{header|Forth}}== |
|||
<syntaxhighlight lang="forth">create a 3 , 2 , 1 , |
|||
: .array ( a len -- ) |
|||
cells bounds do i @ . cell +loop ; \ 3 2 1</syntaxhighlight> |
|||
===FOREACH=== |
|||
The thing about extensible languages is if you need FOREACH, you can have FOREACH. |
|||
The Forth ' operator returns the "execution token" (XT) of a Forth word. An XT can be run with EXECUTE. |
|||
If we apply an appropriate XT to all the elements of an array we have it. |
|||
<syntaxhighlight lang="forth">: FOREACH ( array size XT --) |
|||
Sample output: |
|||
>R \ save execution token on return stack |
|||
<pre> |
|||
CELLS BOUNDS \ convert addr,len -> last,first addresses |
|||
You have /bin in PATH. |
|||
BEGIN |
|||
You have /usr/bin in PATH. |
|||
2DUP > \ test addresses |
|||
</pre> |
|||
WHILE ( last>first ) |
|||
DUP R@ EXECUTE \ apply the execution token to the address |
|||
CELL+ \ move first to the next memory cell |
|||
REPEAT |
|||
R> DROP \ clean return stack |
|||
2DROP \ and data stack |
|||
; |
|||
\ Make an operator to fetch contents of an address and print |
|||
: ? ( addr --) @ . ; |
|||
CREATE A[] 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 , |
|||
\ Usage example: |
|||
A[] 10 ' ? FOREACH </syntaxhighlight> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
< |
<syntaxhighlight lang="fortran">program main |
||
implicit none |
implicit none |
||
Line 994: | Line 1,494: | ||
write(*,'(A)') colors |
write(*,'(A)') colors |
||
end program main</ |
end program main</syntaxhighlight> |
||
=={{header| |
=={{header|friendly interactive shell}}== |
||
Unlike, bash or csh, the PATH variable is automatically converted to real array. |
|||
<lang forth>create a 3 , 2 , 1 , |
|||
<syntaxhighlight lang="fishshell">for path in $PATH |
|||
: .array ( a len -- ) |
|||
echo You have $path in PATH. |
|||
cells bounds do i @ . cell +loop ; \ 3 2 1</lang> |
|||
end</syntaxhighlight> |
|||
Sample output: |
|||
<pre> |
|||
You have /bin in PATH. |
|||
You have /usr/bin in PATH. |
|||
</pre> |
|||
=={{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. |
||
< |
<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| |
=={{header|FutureBasic}}== |
||
<syntaxhighlight lang="futurebasic"> |
|||
We can use ''for'' directly or list iteration. |
|||
<lang fsharp>for i in [1 .. 10] do printfn "%d" i |
|||
window 1 |
|||
List.iter (fun i -> printfn "%d" i) [1 .. 10]</lang> |
|||
void local fn DoIt |
|||
=={{header|Gambas}}== |
|||
CFArrayRef array = @[@"Alpha",@"Bravo",@"Charlie",@"Delta",@"Echo",@"FutureBasic"] |
|||
'''[https://gambas-playground.proko.eu/?gist=cb94500c68749f6f93915f3f10de5a03 Click this link to run this code]''' |
|||
CFStringRef string |
|||
<lang gambas>Public Sub Main() |
|||
Dim siInput As Short[] = [1, 8, 0, 6, 4, 7, 3, 2, 5, 9] |
|||
for string in array |
|||
Dim siTemp As Short |
|||
print string |
|||
next |
|||
end fn |
|||
fn DoIt |
|||
For Each siTemp In siInput.Sort() |
|||
Print siTemp;; |
|||
Next |
|||
HandleEvents |
|||
End</lang> |
|||
</syntaxhighlight> |
|||
Output: |
|||
{{out}} |
|||
<pre> |
<pre> |
||
Alpha |
|||
0 1 2 3 4 5 6 7 8 9 |
|||
Bravo |
|||
Charlie |
|||
Delta |
|||
Echo |
|||
FutureBasic |
|||
</pre> |
</pre> |
||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">for p in AlternatingGroup(4) do |
||
Print(p, "\n"); |
Print(p, "\n"); |
||
od; |
od; |
||
Line 1,049: | Line 1,561: | ||
(1,3,4) |
(1,3,4) |
||
(1,2)(3,4) |
(1,2)(3,4) |
||
(1,4,2)</ |
(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. |
||
< |
<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) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
"for" loop: |
"for" loop: |
||
< |
<syntaxhighlight lang="groovy">def beatles = ["John", "Paul", "George", "Ringo"] |
||
for(name in beatles) { |
for(name in beatles) { |
||
println name |
println name |
||
}</ |
}</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. |
||
< |
<syntaxhighlight lang="groovy">beatles.each { |
||
println it |
println it |
||
}</ |
}</syntaxhighlight> |
||
Output (same for either): |
Output (same for either): |
||
<pre>John |
<pre>John |
||
Line 1,078: | Line 1,590: | ||
=={{header|Halon}}== |
=={{header|Halon}}== |
||
< |
<syntaxhighlight lang="halon">$things = ["Apple", "Banana", "Coconut"]; |
||
foreach ($things as $thing) { |
foreach ($things as $thing) { |
||
echo $thing; |
echo $thing; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad (forM_) |
||
forM_ collect print</ |
forM_ collect print</syntaxhighlight> |
||
which is the same as |
which is the same as |
||
<lang |
<syntaxhighlight lang="haskell">mapM_ print collect</syntaxhighlight> |
||
=={{header|Haxe}}== |
=={{header|Haxe}}== |
||
< |
<syntaxhighlight lang="haxe">var a = [1, 2, 3, 4]; |
||
for(i in a) |
for (i in a) |
||
Sys.println(i);</syntaxhighlight> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<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,103: | Line 1,615: | ||
EDIT(Text=days, ITeM=j, Parse=today) |
EDIT(Text=days, ITeM=j, Parse=today) |
||
WRITE() today |
WRITE() today |
||
ENDDO</ |
ENDDO</syntaxhighlight> |
||
=={{header|Hy}}== |
=={{header|Hy}}== |
||
< |
<syntaxhighlight lang="clojure">(for [x collection] (print x))</syntaxhighlight> |
||
=={{header|Io}}== |
|||
<lang io>collection foreach(println)</lang> |
|||
=={{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. |
||
< |
<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</ |
end</syntaxhighlight> |
||
This loop can be written somewhat more concisely as: |
This loop can be written somewhat more concisely as: |
||
<lang |
<syntaxhighlight lang="icon">every write(!L)</syntaxhighlight> |
||
=={{header|Io}}== |
|||
<syntaxhighlight lang="io">collection foreach(println)</syntaxhighlight> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
<syntaxhighlight lang="j"> echo every i.10 |
|||
<lang J>smoutput each i.10</lang> |
|||
0 |
|||
1 |
|||
2 |
|||
3 |
|||
4 |
|||
5 |
|||
6 |
|||
7 |
|||
8 |
|||
9</syntaxhighlight> |
|||
That said, J's <code>for.</code> provides a "foreach" mechanism. |
|||
<syntaxhighlight lang="J"> {{for_i. i. y do. echo i end.}}10 |
|||
0 |
|||
1 |
|||
2 |
|||
3 |
|||
4 |
|||
5 |
|||
6 |
|||
7 |
|||
8 |
|||
9 |
|||
</syntaxhighlight> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
< |
<syntaxhighlight lang="java">Iterable<Type> collect; |
||
... |
... |
||
for(Type i:collect){ |
for(Type i:collect){ |
||
System.out.println(i); |
System.out.println(i); |
||
}</ |
}</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+}} |
|||
<syntaxhighlight lang="java"> |
|||
Iterable collect; |
|||
... |
|||
collect.forEach(o -> System.out.println(o)); |
|||
</syntaxhighlight> |
|||
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()''': |
||
<syntaxhighlight lang="javascript">"alpha beta gamma delta".split(" ").forEach(function (x) { |
|||
<lang JavaScript>"alpha beta gamma delta".split(' ').forEach( |
|||
function (x) { |
|||
console.log(x); |
console.log(x); |
||
});</syntaxhighlight> |
|||
} |
|||
);</lang> |
|||
Output: |
|||
<pre>alpha |
|||
beta |
|||
gamma |
|||
delta</pre> |
|||
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()''', |
||
<syntaxhighlight lang="javascript">console.log("alpha beta gamma delta".split(" ").map(function (x) { |
|||
<lang JavaScript>console.log("alpha beta gamma delta".split(' ').map( |
|||
function (x) { |
|||
return x.toUpperCase(x); |
return x.toUpperCase(x); |
||
}).join("\n"));</syntaxhighlight> |
|||
} |
|||
).join('\n'));</lang> |
|||
Output: |
|||
<pre>ALPHA |
|||
BETA |
|||
GAMMA |
|||
DELTA</pre> |
|||
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()''' |
||
<syntaxhighlight lang="javascript">console.log("alpha beta gamma delta".split(" ").reduce(function (a, x, i, lst) { |
|||
return lst.length - i + ". " + x + "\n" + a; |
|||
<lang JavaScript>console.log( |
|||
}, ""));</syntaxhighlight> |
|||
"alpha beta gamma delta".split(' ').reduce( |
|||
function (a, x, i, lst) { |
|||
return lst.length - i + '. ' + x + '\n' + a; |
|||
}, '' |
|||
) |
|||
)</lang> |
|||
Output: |
|||
<pre>1. delta |
|||
2. gamma |
|||
3. beta |
|||
4. alpha</pre> |
|||
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. |
||
< |
<syntaxhighlight lang="javascript">for (var a in o) { |
||
print(o[a]); |
print(o[a]); |
||
}</ |
}</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: |
||
< |
<syntaxhighlight lang="javascript">for (var a in o) { |
||
if (o.hasOwnProperty(a)) { |
if (o.hasOwnProperty(a)) { |
||
print(o[a]); |
print(o[a]); |
||
} |
} |
||
}</ |
}</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: |
||
< |
<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);</syntaxhighlight> |
|||
/* |
|||
two |
|||
one |
|||
three |
|||
*/ |
|||
for each (y in h) print(y); |
|||
/* |
|||
2 |
|||
1 |
|||
3 |
|||
*/</lang> |
|||
{{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: |
||
< |
<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);</syntaxhighlight> |
|||
/* |
|||
two |
|||
one |
|||
three |
|||
*/ |
|||
for (y of h) print(y); |
|||
/* |
|||
2 |
|||
1 |
|||
3 |
|||
*/</lang> |
|||
=={{header|Julia}}== |
|||
{{trans|Python}} |
|||
<lang julia>for i in collection |
|||
println(i) |
|||
end</lang> |
|||
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|jq}}== |
=={{header|jq}}== |
||
'''Iterables''': |
'''Iterables''': |
||
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: |
||
< |
<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: |
||
< |
<syntaxhighlight lang="jq">example | .[] |
||
# or equivalently: example[]</ |
# or equivalently: example[]</syntaxhighlight> |
||
< |
<syntaxhighlight lang="jq">{"a":1, "b":2} | .[] |
||
# or equivalently: {"a":1, "b":2}[]</ |
# 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: |
||
< |
<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,260: | Line 1,739: | ||
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: |
||
< |
<syntaxhighlight lang="jq">"abc" | . as $s | range(0;length) | $s[.:.+1] |
||
"abc" | explode | map( [.]|implode) | .[]</ |
"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". |
||
=={{header|Jsish}}== |
|||
Jsi supports ''for of'' for looping over element of an array. |
|||
<syntaxhighlight lang="javascript">for (str of "alpha beta gamma delta".split(' ')) { puts(str); }</syntaxhighlight> |
|||
{{out}} |
|||
<pre>alpha |
|||
beta |
|||
gamma |
|||
delta</pre> |
|||
=={{header|Julia}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="julia">for i in collection |
|||
println(i) |
|||
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. |
|||
=={{header|K}}== |
|||
<syntaxhighlight lang="k"> {`0:$x} ' !10</syntaxhighlight> |
|||
<syntaxhighlight lang="k"> _sin ' (1; 2; 3;)</syntaxhighlight> |
|||
=={{header|Klingphix}}== |
|||
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy |
|||
( -2 "field" 3.14159 ( "this" "that" ) ) len [get ?] for |
|||
" " input</syntaxhighlight> |
|||
{{out}} |
|||
<pre>-2 |
|||
field |
|||
3.14159 |
|||
("this", "that")</pre> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 1,276: | Line 1,788: | ||
greek.forEach { print("$it ") } |
greek.forEach { print("$it ") } |
||
println() |
println() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,283: | Line 1,795: | ||
alpha beta gamma delta |
alpha beta gamma delta |
||
</pre> |
</pre> |
||
=={{header|LabVIEW}}== |
|||
[[LabVIEW]] has a feature known as an Auto-Indexed Tunnel. It is the very small orange box on the lower left of the for loop.<br/>{{VI solution|LabVIEW_Loops_Foreach.png}} |
|||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
{def collection alpha beta gamma delta} |
|||
-> collection |
|||
{S.map {lambda {:i} {br}:i} {collection}} |
|||
-> |
|||
alpha |
|||
beta |
|||
gamma |
|||
delta |
|||
or |
|||
{def S.foreach |
|||
{lambda {:s} |
|||
{if {S.empty? {S.rest :s}} |
|||
then {S.first :s} |
|||
else {S.first :s} {br}{S.foreach {S.rest :s}}}}} |
|||
{S.foreach {collection}} |
|||
-> |
|||
alpha |
|||
beta |
|||
gamma |
|||
delta |
|||
</syntaxhighlight> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
$collection = fn.arrayOf(1, 2, 3) |
|||
# Foreach loop [Works with iterable types (text, collections [array, list])] |
|||
$ele |
|||
foreach($[ele], $collection) { |
|||
fn.println($ele) |
|||
} |
|||
# Foreach function |
|||
# Array: fn.arrayForEach(&arr, func) |
|||
# List: fn.listForEach(&list, func) |
|||
fn.arrayForEach($collection, fn.println) |
|||
</syntaxhighlight> |
|||
=={{header|Lang5}}== |
|||
<syntaxhighlight lang="lang5">: >>say.(*) . ; |
|||
5 iota >>say.</syntaxhighlight> |
|||
=={{header|langur}}== |
|||
A for in loop iterates over values and a for of loop iterates over keys. |
|||
<syntaxhighlight lang="langur"> |
|||
for i in [1, 2, 3] { |
|||
writeln i |
|||
} |
|||
val abc = "abc" |
|||
for i in abc { |
|||
writeln i |
|||
} |
|||
for i of abc { |
|||
writeln abc[i] |
|||
} |
|||
for i in abc { |
|||
writeln cp2s(i) |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1 |
|||
2 |
|||
3 |
|||
97 |
|||
98 |
|||
99 |
|||
97 |
|||
98 |
|||
99 |
|||
a |
|||
b |
|||
c</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">array(1,2,3) => foreach { stdoutnl(#1) }</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lasso">with i in array(1,2,3) do { stdoutnl(#i) }</syntaxhighlight> |
||
=={{header| |
=={{header|LDPL}}== |
||
<syntaxhighlight lang="ldpl">data: |
|||
<lang K> {`0:$x} ' !10</lang> |
|||
fruits is text list |
|||
<lang K> _sin ' (1; 2; 3;)</lang> |
|||
fruit is text |
|||
procedure: |
|||
split "apple banana orange" by " " in fruits |
|||
for each fruit in fruits do |
|||
display fruit lf |
|||
repeat |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
apple |
|||
banana |
|||
orange |
|||
</pre> |
|||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
< |
<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| |
=={{header|LIL}}== |
||
<syntaxhighlight lang="tcl"># Loops/Foreach, in LIL |
|||
[[LabVIEW]] has a feature known as an Auto-Indexed Tunnel. It is the very small orange box on the lower left of the for loop.<br/>{{VI solution|LabVIEW_Loops_Foreach.png}} |
|||
set collection [list 1 2 "three"] |
|||
append collection [list 4 5 six] # appended as a single item in collection |
|||
print "Collection is: $collection" |
|||
# using default "i" variable name set for each item |
|||
=={{header|Lang5}}== |
|||
foreach $collection {print $i} |
|||
<lang lang5>: >>say.(*) . ; |
|||
5 iota >>say.</lang> |
|||
# user named variable in the steps, retrieving accumulated result of loop |
|||
# each loop step quotes two copies of the item |
|||
set newlist [foreach j $collection {quote $j $j}] |
|||
print "Result of second foreach: $newlist"</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ lil loopsForeach.lil |
|||
Collection is: 1 2 three {4 5 six} |
|||
1 |
|||
2 |
|||
three |
|||
4 5 six |
|||
Result of second foreach: {1 1} {2 2} {three three} {4 5 six 4 5 six}</pre> |
|||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<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</ |
end repeat</syntaxhighlight> |
||
A callback-based forEach() can be implemented like this: |
A callback-based forEach() can be implemented like this: |
||
< |
<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,327: | Line 1,957: | ||
call(cbFunc, cbObj, tList[i], i, tList) |
call(cbFunc, cbObj, tList[i], i, tList) |
||
end repeat |
end repeat |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lingo">days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] |
||
forEach(days, #alert, _player)</ |
forEach(days, #alert, _player)</syntaxhighlight> |
||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang="lisaac">"Lisaac loop foreach".split.foreach { word : STRING; |
||
word.print; |
word.print; |
||
'\n'.print; |
'\n'.print; |
||
};</ |
};</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
Livecode's ''for each'' operates on chunks which may be words, items, lines, tokens. Example is for items.< |
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</ |
end repeat</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">foreach [red green blue] [print ?]</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Line 1,350: | Line 1,980: | ||
<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: |
||
< |
<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</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,367: | Line 1,997: | ||
<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. |
||
< |
<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</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,386: | Line 2,016: | ||
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,414: | Line 2,044: | ||
} |
} |
||
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|Mathematica}}/{{header|Wolfram Language}}== |
||
Foreach over list of strings |
Foreach over list of strings |
||
< |
<syntaxhighlight lang="mathematica">s = (StringSplit@Import["ExampleData/USConstitution.txt"])[[1;;7]]; |
||
Do[ |
Do[ |
||
Print@i, |
Print@i, |
||
{i, s} |
{i, s} |
||
]</ |
]</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>We |
<pre>We |
||
Line 1,440: | Line 2,070: | ||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<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; </ |
end; </syntaxhighlight> |
||
< |
<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; </ |
end; </syntaxhighlight> |
||
A vectorized version of the code is |
A vectorized version of the code is |
||
< |
<syntaxhighlight lang="matlab"> printf('%d\n',list1); |
||
printf('%s\n',list2{:}); </ |
printf('%s\n',list2{:}); </syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">for n in [2, 3, 5, 7] do print(n);</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|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,462: | Line 2,092: | ||
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: |
||
< |
<syntaxhighlight lang="metafont">for x = "mary", "had", "a", "little", "lamb": message x; endfor |
||
end</ |
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 |
||
< |
<syntaxhighlight lang="metafont">for x = for i = 1 upto 9: a[i], endfor, a[10]: show x; endfor |
||
end</ |
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}}== |
|||
{{works with|min|0.19.3}} |
|||
<syntaxhighlight lang="min">(1 2 3) 'puts foreach</syntaxhighlight> |
|||
=={{header|MiniScript}}== |
|||
<syntaxhighlight lang="miniscript">for i in collection |
|||
print i |
|||
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. |
|||
=={{header|MOO}}== |
=={{header|MOO}}== |
||
< |
<syntaxhighlight lang="moo">things = {"Apple", "Banana", "Coconut"}; |
||
for thing in (things) |
for thing in (things) |
||
player:tell(thing); |
player:tell(thing); |
||
endfor</ |
endfor</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
|||
Like Python, Nanoquery supports for...in syntax for list types and strings. |
|||
<syntaxhighlight lang="nanoquery">for item in collection |
|||
println item |
|||
end</syntaxhighlight> |
|||
<strong>Some examples:</strong> |
|||
<syntaxhighlight lang="nanoquery">for n in {1,3,5,7,9} |
|||
print n + " " |
|||
end |
|||
println |
|||
for char in "test string" |
|||
print char |
|||
end |
|||
println</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1 3 5 7 9 |
|||
test string</pre> |
|||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
This works on anything which implements the IEnumerable interface. |
This works on anything which implements the IEnumerable interface. |
||
< |
<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");</ |
foreach (i in [5, 10 .. 100]) Write($"$i\t");</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|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,500: | Line 2,160: | ||
loop while daysi.hasNext |
loop while daysi.hasNext |
||
say daysi.next |
say daysi.next |
||
end</ |
end</syntaxhighlight> |
||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">(map println '(Apple Banana Coconut))</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
<syntaxhighlight lang="nim">let list = ["lorem", "ipsum", "dolor"] |
|||
<lang nim>var list: seq[string] = @[] |
|||
for item in list: |
|||
list.add("lorem") |
|||
echo item</syntaxhighlight> |
|||
list.add("ipsum") |
|||
{{out}} |
|||
list.add("dolor") |
|||
<pre>lorem |
|||
for i in items(list): |
|||
echo(i)</lang> |
|||
Output: |
|||
<pre> |
|||
lorem |
|||
ipsum |
ipsum |
||
dolor |
dolor</pre> |
||
=={{header|Nu}}== |
|||
<syntaxhighlight lang="nu"> |
|||
let l = [a b c d] |
|||
for x in $l {print $x} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
a |
|||
b |
|||
c |
|||
d |
|||
</pre> |
</pre> |
||
=={{header|Objeck}}== |
|||
<syntaxhighlight lang="objeck">fruits := ["Apple", "Banana", "Coconut"]; |
|||
each(i : fruits) { |
|||
fruits[i]->PrintLine(); |
|||
};</syntaxhighlight> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
Line 1,523: | Line 2,196: | ||
{{works with|GNUstep}} |
{{works with|GNUstep}} |
||
{{works with|Cocoa}} |
{{works with|Cocoa}} |
||
< |
<syntaxhighlight lang="objc">NSArray *collect; |
||
//... |
// ... |
||
for(Type i in collect){ |
for (Type i in collect) { |
||
NSLog(@"%@", i); |
NSLog(@"%@", i); |
||
}</ |
}</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}} |
||
< |
<syntaxhighlight lang="objc">NSArray *collect; |
||
//... |
// ... |
||
NSEnumerator *enm = [collect objectEnumerator]; |
NSEnumerator *enm = [collect objectEnumerator]; |
||
id i; |
id i; |
||
while |
while ((i = [enm nextObject])) { |
||
// do something with object i |
// do something with object i |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Objeck}}== |
|||
<lang objeck>fruits := ["Apple", "Banana", "Coconut"]; |
|||
each(i : fruits) { |
|||
fruits[i]->PrintLine(); |
|||
};</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
List of integers: |
List of integers: |
||
< |
<syntaxhighlight lang="ocaml">List.iter |
||
(fun i -> Printf.printf "%d\n" i) |
(fun i -> Printf.printf "%d\n" i) |
||
collect_list</ |
collect_list</syntaxhighlight> |
||
Array of integers: |
Array of integers: |
||
< |
<syntaxhighlight lang="ocaml">Array.iter |
||
(fun i -> Printf.printf "%d\n" i) |
(fun i -> Printf.printf "%d\n" i) |
||
collect_array</ |
collect_array</syntaxhighlight> |
||
=={{header|Oforth}}== |
|||
<lang Oforth>: printMonths | m | Date.Months forEach: m [ m . ] ;</lang> |
|||
But, apply can be used instead of a loop : |
|||
<lang Oforth>#. Date.Months apply</lang> |
|||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<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,571: | Line 2,231: | ||
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</ |
endfor</syntaxhighlight> |
||
We can also iterate over structures: |
We can also iterate over structures: |
||
< |
<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</ |
endfor</syntaxhighlight> |
||
=={{header|Oforth}}== |
|||
<syntaxhighlight lang="oforth">: printMonths | m | Date.Months forEach: m [ m . ] ;</syntaxhighlight> |
|||
But, apply can be used instead of a loop : |
|||
<syntaxhighlight lang="oforth">#. Date.Months apply</syntaxhighlight> |
|||
=={{header|Ol}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
(for-each print '(1 3 4 2)) |
|||
(print) |
|||
(for-each (lambda (a b c) (print a "-" b "/" c)) |
|||
'(1 2 3 4) |
|||
'(5 6 7 8) |
|||
'(a b x z)) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
3 |
|||
4 |
|||
2 |
|||
1-5/a |
|||
2-6/b |
|||
3-7/x |
|||
4-8/z |
|||
</pre> |
|||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
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. |
||
< |
<syntaxhighlight lang="oorexx">/* Rexx */ |
||
say |
say |
||
say 'Loops/Foreach' |
say 'Loops/Foreach' |
||
Line 1,595: | Line 2,284: | ||
say out~strip() |
say out~strip() |
||
exit</ |
exit</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
Line 1,603: | Line 2,292: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
MyList = [1 2 3 4] |
MyList = [1 2 3 4] |
||
in |
in |
||
Line 1,609: | Line 2,298: | ||
%% or: |
%% or: |
||
for E in MyList do {Show E} end</ |
for E in MyList do {Show E} end</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">for(i=1,#v,print(v[i]))</syntaxhighlight> |
||
or (PARI/GP >= 2.4) |
or (PARI/GP >= 2.4) |
||
< |
<syntaxhighlight lang="parigp">apply(x->print(x),v)</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
See [[Loops/Foreach#Delphi | Delphi]] |
See [[Loops/Foreach#Delphi | Delphi]] |
||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
## |
|||
foreach var s in |'Pascal','ABC','.NET'| do |
|||
Print(s); |
|||
</syntaxhighlight> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">foreach my $i (@collection) { |
||
print "$i\n"; |
print "$i\n"; |
||
}</ |
}</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: |
||
< |
<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: |
||
< |
<syntaxhighlight lang="perl">foreach $l ( "apples", "bananas", "cherries" ) { |
||
print "I like $l\n"; |
print "I like $l\n"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Perl 6}}== |
|||
{{works with|Rakudo|2015.10-40}} |
|||
<lang perl6>say $_ for @collection;</lang> |
|||
Perl 6 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> |
|||
Perl 6 will do it's best to put the topic at the right spot. |
|||
<lang perl6>.say for @collection; |
|||
for @collection { .say };</lang> |
|||
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 per6>@collection>>.say; |
|||
@collection>>.=&infix:<+>(2); # increment each element by 2</lang> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--<syntaxhighlight lang="phix">--> |
|||
<lang Phix>sequence s = {-2,"field",3.14159268979,{"this","that"}} |
|||
<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> |
|||
for i=1 to length(s) do |
|||
<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> |
|||
?s[i] |
|||
<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> |
|||
end for</lang> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<!--</syntaxhighlight>--> |
|||
=={{header|PHL}}== |
=={{header|PHL}}== |
||
< |
<syntaxhighlight lang="phl">var numbers = 1..10; |
||
numbers each # (number) [ |
numbers each # (number) [ |
||
printf("%i\n", number); |
printf("%i\n", number); |
||
];</ |
];</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">foreach ($collect as $i) { |
||
echo "$i\n"; |
echo "$i\n"; |
||
} |
} |
||
Line 1,668: | Line 2,354: | ||
foreach ($collect as $key => $i) { |
foreach ($collect as $key => $i) { |
||
echo "\$collect[$key] = $i\n"; |
echo "\$collect[$key] = $i\n"; |
||
}</ |
}</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}}== |
||
< |
<syntaxhighlight lang="picolisp">(mapc println '(Apple Banana Coconut))</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<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"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Iterating over the keys and values of a mapping (dictionary): |
Iterating over the keys and values of a mapping (dictionary): |
||
< |
<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"); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<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;</ |
end;</syntaxhighlight> |
||
=={{header|Plain English}}== |
|||
<syntaxhighlight lang="plainenglish">To run: |
|||
Start up. |
|||
Create a list. |
|||
Write each entry in the list to the console. |
|||
Destroy the list. |
|||
Wait for the escape key. |
|||
Shut down. |
|||
An entry is a thing with a number. |
|||
A list is some entries. |
|||
To add a number to a list: |
|||
Allocate memory for an entry. |
|||
Put the number into the entry's number. |
|||
Append the entry to the list. |
|||
To create a list: |
|||
Add 1 to the list. |
|||
Add 2 to the list. |
|||
Add 3 to the list. |
|||
Add 6 to the list. |
|||
Add 7 to the list. |
|||
Add 9 to the list. |
|||
To write an entry to the console: |
|||
Convert the entry's number to a string. |
|||
Write the string to the console. |
|||
To write each entry in a list to the console: |
|||
Get an entry from the list. |
|||
Loop. |
|||
If the entry is nil, exit. |
|||
Write the entry to the console. |
|||
Put the entry's next into the entry. |
|||
Repeat.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
2 |
|||
3 |
|||
6 |
|||
7 |
|||
9 |
|||
</pre> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Iteration over list: |
Iteration over list: |
||
< |
<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;</ |
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: |
||
< |
<syntaxhighlight lang="postscript">[1 5 3 2] { = } forall |
||
(abc) { = } forall</ |
(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: |
||
< |
<syntaxhighlight lang="postscript"><</a 25 /b 42>> { |
||
exch (Key: ) print |
exch (Key: ) print |
||
= |
= |
||
(Value: ) print |
(Value: ) print |
||
= |
= |
||
} forall</ |
} 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 1,723: | Line 2,456: | ||
Write-Host "$color" -ForegroundColor $color |
Write-Host "$color" -ForegroundColor $color |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 1,746: | Line 2,479: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
For example : |
For example : |
||
< |
<syntaxhighlight lang="prolog">?- foreach(member(X, [red,green,blue,black,white]), writeln(X)). |
||
red |
red |
||
green |
green |
||
Line 1,753: | Line 2,486: | ||
white |
white |
||
true. |
true. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">for i in collection: |
||
print i</ |
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: |
||
< |
<syntaxhighlight lang="python">lines = words = characters = 0 |
||
f = open('somefile','r') |
f = open('somefile','r') |
||
for eachline in f: |
for eachline in f: |
||
Line 1,772: | Line 2,504: | ||
characters += 1 |
characters += 1 |
||
print lines, words, characters</ |
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 1,778: | Line 2,510: | ||
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: |
||
< |
<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 1,784: | Line 2,516: | ||
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]))</ |
print("%s: %s" % (k, d[k]))</syntaxhighlight> |
||
{{works with|Python|2.x}} |
{{works with|Python|2.x}} |
||
< |
<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]))</ |
print("%s: %s" % (k, d[k]))</syntaxhighlight> |
||
=={{header|Quackery}}== |
|||
<syntaxhighlight lang="quackery">$ "Sweet Boom Pungent Prickle Orange" nest$ |
|||
witheach [ i times sp echo$ cr ]</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> Sweet |
|||
Boom |
|||
Pungent |
|||
Prickle |
|||
Orange |
|||
</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">a <- list("First", "Second", "Third", 5, 6) |
||
for(i in a) print(i)</ |
for(i in a) print(i)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
Line 1,807: | Line 2,551: | ||
(for ([i sequence]) |
(for ([i sequence]) |
||
(displayln i)) |
(displayln i)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
{{works with|Rakudo|2015.10-40}} |
|||
<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>. |
|||
<syntaxhighlight lang="raku" line>for @collection -> $currentElement { say $currentElement; }</syntaxhighlight> |
|||
Raku will do it's best to put the topic at the right spot. |
|||
<syntaxhighlight lang="raku" line>.say for @collection; |
|||
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. |
|||
<syntaxhighlight lang="raku" line>@collection>>.say; |
|||
@collection>>.=&infix:<+>(2); # increment each element by 2</syntaxhighlight> |
|||
=={{header|REBOL}}== |
=={{header|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 1,822: | Line 2,579: | ||
; the list from the current position. |
; the list from the current position. |
||
forall x [prin rejoin [x/1 "day "]] print ""</ |
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 1,828: | Line 2,585: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<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 1,852: | Line 2,609: | ||
20 Jeff 40 |
20 Jeff 40 |
||
Jeff 40 |
Jeff 40 |
||
40</ |
40</syntaxhighlight> |
||
=={{header|ReScript}}== |
|||
<syntaxhighlight lang="rescript">let fruits = ["apple", "banana", "coconut"] |
|||
Js.Array2.forEach(fruits, f => Js.log(f))</syntaxhighlight> |
|||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
Retro has |
Retro has '''for-each''' combinators for operating on elements of various data structures. |
||
<lang Retro>( Strings: this will display the ASCII code for each character in a string ) |
|||
"This is a message" [ @ putn space ] ^types'STRING each@ |
|||
<syntaxhighlight lang="retro"># Strings |
|||
( Array: display each element ) |
|||
needs array' |
|||
[ 1 2 3 ] ^array'fromQuote [ @ putn space ] ^types'ARRAY each@ |
|||
This will display the ASCII code for each character in a string |
|||
( Linked List: using the dictionary as an example, display each name ) |
|||
last [ d->name puts space ] ^types'LIST each@ |
|||
~~~ |
|||
( Generic Buffers; display each value in a buffer ) |
|||
'This_is_a_message [ n:put sp ] s:for-each |
|||
create foo |
|||
~~~ |
|||
1 , 3 , 5 , |
|||
# Array |
|||
foo 3 [ @ putn space ] ^types'BUFFER each@</lang> |
|||
Display each element |
|||
~~~ |
|||
{ #1 #2 #3 } [ n:put sp ] a:for-each |
|||
~~~ |
|||
# Linked List |
|||
Using the dictionary as an example, display each name |
|||
~~~ |
|||
&Dictionary [ d:name s:put sp ] d:for-each |
|||
~~~ |
|||
</syntaxhighlight> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<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.*/</ |
/*stick a fork in it, we're done.*/</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|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|RPL}}== |
|||
In RPL, « printing » a collection means sending it to the printer, if you have one. To just output the items of a list, you put them into the stack, like this: |
|||
≪ { "one" "two" "three" "four" "five" } LIST→ DROP ≫ |
|||
If the idea is to do more than displaying the items, the usual way is a <code>FOR..NEXT</code> loop |
|||
≪ { "one" "two" "three" "four" "five" } → collection |
|||
≪ 1 collection SIZE '''FOR''' j |
|||
collection j GET |
|||
''(do something with the item here)'' |
|||
'''NEXT''' |
|||
≫ ≫ |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">for i in collection do |
||
puts i |
puts i |
||
end</ |
end</syntaxhighlight> |
||
This is syntactic sugar for: |
This is syntactic sugar for: |
||
< |
<syntaxhighlight lang="ruby">collection.each do |i| |
||
puts i |
puts i |
||
end</ |
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. |
||
< |
<syntaxhighlight lang="rust">let collection = vec![1,2,3,4,5]; |
||
for elem in collection { |
for elem in collection { |
||
println!("{}", elem); |
println!("{}", elem); |
||
}</ |
}</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. |
||
< |
<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 1,921: | Line 2,702: | ||
// for immut_ref in collection.iter() { |
// for immut_ref in collection.iter() { |
||
println!("{}", *immut_ref); |
println!("{}", *immut_ref); |
||
}</ |
}</syntaxhighlight> |
||
Since Rust 1.21 foreach can be used explicitly executing a closure on each element. |
|||
<syntaxhighlight lang="rust">let collection = vec![1, 2, 3, 4, 5]; |
|||
collection.iter().for_each(|elem| println!("{}", elem));</syntaxhighlight> |
|||
=={{header|Salmon}}== |
=={{header|Salmon}}== |
||
< |
<syntaxhighlight lang="salmon">iterate (x; ["Red", "Green", "Blue"]) |
||
x!;</ |
x!;</syntaxhighlight> |
||
output: |
output: |
||
<pre> |
<pre> |
||
Line 1,934: | Line 2,719: | ||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
< |
<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 1,944: | Line 2,729: | ||
s=sum(of a{*}); |
s=sum(of a{*}); |
||
put s; |
put s; |
||
run;</ |
run;</syntaxhighlight> |
||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<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 1,956: | Line 2,741: | ||
end; |
end; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">val collection = Array(1, 2, 3, 4) |
||
collection.foreach(println)</syntaxhighlight> |
|||
for (element <- collection) |
|||
println(element)</lang> |
|||
Alternatively: |
Alternatively: |
||
< |
<syntaxhighlight lang="scala">(element <- 1 to 4).foreach(println)</syntaxhighlight> |
||
println(element)</lang> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
List: |
List: |
||
< |
<syntaxhighlight lang="scheme">(for-each |
||
(lambda (i) (display i) (newline)) |
(lambda (i) (display i) (newline)) |
||
the_list)</ |
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</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a |
<pre>a |
||
Line 1,984: | Line 2,767: | ||
=={{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. |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
var array string: things is [] ("Apple", "Banana", "Coconut"); |
var array string: things is [] ("Apple", "Banana", "Coconut"); |
||
Line 1,995: | Line 2,778: | ||
writeln(thing); |
writeln(thing); |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Self}}== |
=={{header|Self}}== |
||
< |
<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}}== |
||
< |
<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;</ |
end loop;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
'''foreach''' loop: |
'''foreach''' loop: |
||
< |
<syntaxhighlight lang="ruby">foreach [1,2,3] { |i| |
||
say i |
say i |
||
}</ |
}</syntaxhighlight> |
||
'''for-in''' loop: |
'''for-in''' loop: |
||
< |
<syntaxhighlight lang="ruby">for i in [1,2,3] { |
||
say i |
say i |
||
}</ |
}</syntaxhighlight> |
||
'''.each''' method: |
'''.each''' method: |
||
< |
<syntaxhighlight lang="ruby">[1,2,3].each { |i| |
||
say i |
say i |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">c do: [| :obj | print: obj].</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<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). |
|||
Most modern Smalltalks allow for a selector symbol to be sent a <tt>value:</tt> message; which allows for the very compact: |
|||
<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) |
|||
<syntaxhighlight lang="smalltalk">(1 to:6 by:2) do:#displayNl. |
|||
'hello' do:#displayNl. |
|||
(Integer primesUpTo:100) do:#displayNl. |
|||
'/' asFilename directoryContents do:#displayNl. |
|||
((Smalltalk allClasses collect:#name) asSortedCollection to:2) do:#displayNl. |
|||
funnyClassLessObject := Plug new |
|||
respondTo:#do: |
|||
with:[:arg | |
|||
arg value:'look ma'. |
|||
arg value:'no classes needed']. |
|||
funnyClassLessObject do:#displayNl. |
|||
etc.</syntaxhighlight> |
|||
{{out}} |
|||
1 |
|||
3 |
|||
5 |
|||
h |
|||
e |
|||
l |
|||
l |
|||
o |
|||
2 |
|||
3 |
|||
5 |
|||
... |
|||
97 |
|||
home |
|||
usr |
|||
... |
|||
tmp |
|||
cores |
|||
AAAARecord |
|||
AATree |
|||
look ma |
|||
no classes needed |
|||
=={{header|Snabel}}== |
=={{header|Snabel}}== |
||
Prints foo, bar & baz followed by newlines. |
Prints foo, bar & baz followed by newlines. |
||
< |
<syntaxhighlight lang="snabel">['foo' 'bar' 'baz'] &say for</syntaxhighlight> |
||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
Line 2,038: | Line 2,862: | ||
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: |
||
< |
<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); |
||
});</ |
});</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
List of integers: |
List of integers: |
||
< |
<syntaxhighlight lang="sml">app |
||
(fn i => print (Int.toString i ^ "\n")) |
(fn i => print (Int.toString i ^ "\n")) |
||
collect_list</ |
collect_list</syntaxhighlight> |
||
Array of integers: |
Array of integers: |
||
< |
<syntaxhighlight lang="sml">Array.app |
||
(fn i => print (Int.toString i ^ "\n")) |
(fn i => print (Int.toString i ^ "\n")) |
||
collect_array</ |
collect_array</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<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'" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Suneido}}== |
=={{header|Suneido}}== |
||
< |
<syntaxhighlight lang="suneido">for i in #(1, 2, 3) |
||
Print(i)</ |
Print(i)</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">for i in [1,2,3] { |
||
print(i) |
print(i) |
||
}</ |
}</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+}} |
||
< |
<syntaxhighlight lang="swift">[1,2,3].forEach { |
||
print($0) |
print($0) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|SystemVerilog}}== |
=={{header|SystemVerilog}}== |
||
< |
<syntaxhighlight lang="systemverilog">program main; |
||
int values[$]; |
int values[$]; |
||
Line 2,084: | Line 2,909: | ||
end |
end |
||
end |
end |
||
endprogram</ |
endprogram</syntaxhighlight> |
||
=={{header|Tailspin}}== |
|||
Stream them |
|||
<syntaxhighlight lang="tailspin"> |
|||
['a', 'b', 'c'] ... -> !OUT::write |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>abc</pre> |
|||
Lists/arrays can be put through an array transform to get the index as well |
|||
<syntaxhighlight lang="tailspin"> |
|||
['a', 'b', 'c'] -> \[i]('$i;:$; |
|||
' -> !OUT::write \) -> !VOID |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1:a |
|||
2:b |
|||
3:c |
|||
</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">foreach i {foo bar baz} { |
||
puts "$i" |
puts "$i" |
||
}</ |
}</syntaxhighlight> |
||
Note that <tt>foreach</tt> also accepts multiple variables: |
Note that <tt>foreach</tt> also accepts multiple variables: |
||
< |
<syntaxhighlight lang="tcl">foreach {x y} {1 2 3 4} { |
||
puts "$x,$y" |
puts "$x,$y" |
||
}</ |
}</syntaxhighlight> |
||
And also multiple lists: |
And also multiple lists: |
||
< |
<syntaxhighlight lang="tcl">foreach i {1 2 3} j {a b c} { |
||
puts "$i,$j" |
puts "$i,$j" |
||
}</ |
}</syntaxhighlight> |
||
Or any combination of variables/list: |
Or any combination of variables/list: |
||
< |
<syntaxhighlight lang="tcl">foreach i {1 2 3} {x y} {a b c d e f} { |
||
puts "$i,$x,$y" |
puts "$i,$x,$y" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Trith}}== |
=={{header|Trith}}== |
||
< |
<syntaxhighlight lang="trith">[1 2 3 4 5] [print] each</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|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</ |
ENDLOOP</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,127: | Line 2,971: | ||
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}} |
||
< |
<syntaxhighlight lang="bash">for file in *.sh; do |
||
echo "filename is $file" |
echo "filename is $file" |
||
done</ |
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}} |
||
< |
<syntaxhighlight lang="bash">PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin |
||
oldifs=$IFS |
oldifs=$IFS |
||
Line 2,139: | Line 2,983: | ||
echo search $dir |
echo search $dir |
||
done |
done |
||
IFS=$oldifs</ |
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}} |
||
< |
<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</ |
done</syntaxhighlight> |
||
{{works with|pdksh|5.2.14}} |
{{works with|pdksh|5.2.14}} |
||
< |
<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</ |
done</syntaxhighlight> |
||
==={{header|C Shell}}=== |
==={{header|C Shell}}=== |
||
< |
<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</ |
end</syntaxhighlight> |
||
=={{header|V}}== |
=={{header|V}}== |
||
< |
<syntaxhighlight lang="v">[1 2 3] [puts] step</syntaxhighlight> |
||
=={{header| |
=={{header|Vala}}== |
||
<syntaxhighlight lang="vala">List<string> things = new List<string> (); |
|||
<lang vbscript>items = Array("Apple", "Orange", "Banana") |
|||
things.append("Apple"); |
|||
things.append("Banana"); |
|||
For Each x In items |
|||
things.append("Coconut"); |
|||
WScript.Echo x |
|||
Next</lang> |
|||
foreach (string thing in things) |
|||
{ |
|||
stdout.printf("%s\n", thing); |
|||
}</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. |
||
< |
<syntaxhighlight lang="vim">for i in ["alpha", "beta", 42, 5.54] |
||
echo i |
echo i |
||
endfor</ |
endfor</syntaxhighlight> |
||
=={{header|V (Vlang)}}== |
|||
{{trans|go}} |
|||
<syntaxhighlight lang="v (vlang)">fn print_all(values []int) { |
|||
for i, x in values { |
|||
println("Item $i = $x") |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="wart">each x '(1 2 3) |
||
prn x</ |
prn x</syntaxhighlight> |
||
=={{header|WDTE}}== |
=={{header|WDTE}}== |
||
< |
<syntaxhighlight lang="wdte">let a => import 'arrays'; |
||
let s => import 'stream'; |
let s => import 'stream'; |
||
Line 2,186: | Line 3,042: | ||
-> s.map (io.writeln io.stdout) |
-> s.map (io.writeln io.stdout) |
||
-> s.drain |
-> s.drain |
||
;</ |
;</syntaxhighlight> |
||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">for (f in ["apples", "oranges", "pears"]) System.print(f)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
apples |
|||
oranges |
|||
pears |
|||
</pre> |
|||
=={{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. |
||
< |
<syntaxhighlight lang="lisp">(FOR-EACH PRINT '(CYRUS CAMBYSES DARIUS XERXES ARTAXERXES))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>CYRUS |
<pre>CYRUS |
||
Line 2,200: | Line 3,066: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
Translation of C example: |
Translation of C example: |
||
< |
<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)]; |
||
]</ |
]</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. |
||
< |
<syntaxhighlight lang="xml"><fo:block font-weight="bold">Adults:</fo:block> |
||
<xsl:for-each select="person[@age >= 21]"> |
<xsl:for-each select="person[@age >= 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></ |
</xsl:for-each></syntaxhighlight> |
||
=={{header|zig}}== |
|||
<syntaxhighlight lang="zig">const warn = @import("std").debug.warn; |
|||
pub fn main() void { |
|||
const items = [_]i16{ 0, 1, 1, 2, 3, 5, 8 }; |
|||
for (items) |i| { |
|||
warn("{}\n", .{i}); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|XPL0}} |
{{trans|XPL0}} |
||
< |
<syntaxhighlight lang="zkl">foreach c in (T("Red","Green","Blue","Black","White")) |
||
{ print(c," "); }</ |
{ 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. |
||
< |
<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) }</ |
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,236: | Line 3,114: | ||
356 |
356 |
||
</pre> |
</pre> |
||
=={{header|Zig}}== |
|||
<syntaxhighlight lang="zig">const std = @import("std"); |
|||
pub fn main() !void { |
|||
const stdout_wr = std.io.getStdOut().writer(); |
|||
// 1. Index element index sizes are comptime-known |
|||
const a1: []const u8 = &[_]u8{ 'a', 'b', 'c' }; |
|||
// also works with slices |
|||
//const a2: [] u8 = &a1; |
|||
for (a1) |el_a| |
|||
try stdout_wr.print("{c}\n", .{el_a}); |
|||
// 2. Index element index sizes are not comptime-known |
|||
// Convention is to provide a `next()` method. |
|||
// TODO |
|||
}</syntaxhighlight> |
|||
{{omit from|GUISS}} |
{{omit from|GUISS}} |
||
{{omit from|PL/0}} |
|||
{{omit from|Tiny BASIC}} |
Latest revision as of 16:10, 28 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
- Related tasks
- Loop over multiple arrays simultaneously
- Loops/Break
- Loops/Continue
- Loops/Do-while
- Loops/Downward for
- Loops/For
- Loops/For with a specified step
- Loops/Foreach
- Loops/Increment loop index within loop body
- Loops/Infinite
- Loops/N plus one half
- Loops/Nested
- Loops/While
- Loops/with multiple ranges
- Loops/Wrong ranges
11l
V things = [‘Apple’, ‘Banana’, ‘Coconut’]
L(thing) things
print(thing)
ACL2
(defun print-list (xs)
(if (endp xs)
nil
(prog2$ (cw "~x0~%" (first xs))
(print-list (rest xs)))))
> (print-list (list 1 "a" 1/2 (list 1 2) 'sym)) 1 "a" 1/2 (1 2) SYM NIL
Action!
In Action! there is no for-each loop.
PROC Main()
DEFINE PTR="CARD"
BYTE i
PTR ARRAY items(10)
items(0)="First" items(1)="Second"
items(2)="Third" items(3)="Fourth"
items(4)="Fifth" items(5)="Sixth"
items(6)="Seventh" items(7)="Eighth"
items(8)="Ninth" items(9)="Tenth"
PrintE("In Action! there is no for-each loop")
PutE()
FOR i=0 TO 9
DO
PrintE(items(i))
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
In Action! there is no for-each loop First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth
Ada
arrays
with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
procedure For_Each is
A : array (1..5) of Integer := (-1, 0, 1, 2, 3);
begin
for Num in A'Range loop
Put( A (Num) );
end loop;
end For_Each;
Alternative solution (Ada 2012):
for Item of A loop
Put( Item );
end loop;
doubly linked lists
with Ada.Integer_Text_IO, Ada.Containers.Doubly_Linked_Lists;
use Ada.Integer_Text_IO, Ada.Containers;
procedure Doubly_Linked_List is
package DL_List_Pkg is new Doubly_Linked_Lists (Integer);
use DL_List_Pkg;
procedure Print_Node (Position : Cursor) is
begin
Put (Element (Position));
end Print_Node;
DL_List : List;
begin
DL_List.Append (1);
DL_List.Append (2);
DL_List.Append (3);
-- Iterates through every node of the list.
DL_List.Iterate (Print_Node'Access);
end Doubly_Linked_List;
vectors
with Ada.Integer_Text_IO, Ada.Containers.Vectors;
use Ada.Integer_Text_IO, Ada.Containers;
procedure Vector_Example is
package Vector_Pkg is new Vectors (Natural, Integer);
use Vector_Pkg;
procedure Print_Element (Position : Cursor) is
begin
Put (Element (Position));
end Print_Element;
V : Vector;
begin
V.Append (1);
V.Append (2);
V.Append (3);
-- Iterates through every element of the vector.
V.Iterate (Print_Element'Access);
end Vector_Example;
Aikido
Aikido's foreach
loop allows iteration through multiple value types.
strings
var str = "hello world"
foreach ch str { // you can also use an optional 'in'
println (ch) // one character at a time
}
vectors
var vec = [1,2,3,4]
foreach v vec { // you can also use an optional 'in'
println (v)
}
maps
var cities = {"San Ramon": 50000, "Walnut Creek": 70000, "San Francisco": 700000} // map literal
foreach city cities {
println (city.first + " has population " + city.second)
}
integers
foreach i 100 {
println (i) // prints values 0..99
}
foreach i 10..20 {
println (i) // prints values 10..20
}
var a = 20
var b = 10
foreach i a..b {
println (i) // prints values from a to b (20..10)
}
Objects
Aikido allows definition of a foreach
operator for an object. In this example we define a single linked list and a foreach operator to iterate through it
class List {
class Element (public data) {
public var next = null
}
var start = null
public function insert (data) {
var element = new Element (data)
element.next = start
start = element
}
public operator foreach (var iter) {
if (typeof(iter) == "none") { // first iteration
iter = start
return iter.data
} elif (iter.next == null) { // check for last iteration
iter = none
} else {
iter = iter.next // somewhere in the middle
return iter.data
}
}
}
var list = new List()
list.insert (1)
list.insert (2)
list.insert (4)
foreach n list {
println (n)
}
Coroutines
Aikido supports coroutines. The foreach operator may be used to iterate thorough the generated values.
// coroutine to generate the squares of a sequence of numbers
function squares (start, end) {
for (var i = start ; i < end ; i++) {
yield i*i
}
}
var start = 10
var end = 20
foreach s squares (start, end) {
println (s)
}
Files
If you open a file you can iterate through all the lines
var s = openin ("input.txt")
foreach line s {
print (line)
}
Enumerations
enum Color {
RED, GREEN, BLUE
}
foreach color Color {
println (color)
}
Aime
# iterate over a list of integers
integer i, v;
for (i, v in list(2, 3, 5, 7, 11, 13, 17, 18)) {
}
ALGOL 68
[]UNION(STRING, INT, PROC(REF FILE)VOID) collection = ("Mary","Had",1,"little","lamb.",new line);
FOR index FROM LWB collection TO UPB collection DO
print((collection[index]," "))
OD
Output:
Mary Had +1 little lamb.
ALGOL 68S has a reserved word FOREACH that is used to break arrays in to portions, and process in parallel.
ALGOL 68RS and Algol68toc have a FORALL loop, the following is equivalent to the example above:
FORALL c IN collection DO
print((c," "))
OD
Amazing Hopper
#include <jambo.h>
Main
things = {}, len list=0
Set ' 100,200,300,"Hello world!", -3,-2,-1 ' Apndlist 'things'
Let ' len list := Length(things) '
Printnl ' "\nNormal count:\n" '
For each( n, things, len list )
Printnl ' "Thing : ", n '
Next
Printnl ' "\n\nReverse count:\n" '
For each reverse ( n, things, len list )
Printnl ' "Thing : ", n '
Next
End
- Output:
Normal count: Thing : 100 Thing : 200 Thing : 300 Thing : Hello world! Thing : -3 Thing : -2 Thing : -1 Reverse count: Thing : -1 Thing : -2 Thing : -3 Thing : Hello world! Thing : 300 Thing : 200 Thing : 100
AmigaE
PROC main()
DEF a_list : PTR TO LONG, a
a_list := [10, 12, 14]
FOR a := 0 TO ListLen(a_list)-1
WriteF('\d\n', a_list[a])
ENDFOR
-> if the "action" fits a single statement, we can do instead
ForAll({a}, a_list, `WriteF('\d\n', a))
ENDPROC
Apex
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (Integer i : myInts) {
System.debug(i);
}
AppleScript
repeat with fruit in {"Apple", "Orange", "Banana"}
log contents of fruit
end repeat
Arturo
arr: ["one" "two" "three"]
dict: #[
name: "John"
surname: "Doe"
age: 34
]
loop arr 'item ->
print item
loop dict [key val]->
print [key "=>" val]
- Output:
one two three name => John surname => Doe age => 34
AutoHotkey
string = mary,had,a,little,lamb
Loop, Parse, string, `,
MsgBox %A_LoopField%
AWK
The for (element_index in array)
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).
BEGIN {
split("Mary had a little lamb", strs, " ")
for(el in strs) {
print strs[el]
}
}
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, which uses indexes from 1. So to iterate over the array's elements in the right order, a normal loop can be used:
BEGIN {
n = split("Mary had a little lamb", strs, " ")
for(i=1; i <= n; i++) {
print strs[i]
}
}
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:
# This will not work
BEGIN {
for (el in "apples","bananas","cherries") {
print "I like " el
}
}
Bait
`for-in` loops work with both builtin container types (arrays and maps). They allow to iterate the indices/keys and values.
fun for_in_array() {
arr := ['1st', '2nd', '3rd']
// Iterate over array indices and elements
for i, val in arr {
println('${i}: ${val}')
}
// Using only one variable will iterate over the elements
for val in arr {
println(val)
}
// To only iterate over the indices, use `_` as the second variable name.
// `_` is a special variable that will ignore any assigned value
for i, _ in arr {
println(i)
}
}
fun for_in_map() {
nato_abc := map{
'a': 'Alpha'
'b': 'Bravo'
'c': 'Charlie'
'd': 'Delta'
}
// Iterate over map keys and values.
// Note that, unlike arrays, only the two-variable variant is allowed
for key, val in nato_abc {
println('${key}: ${val}')
}
}
fun main() {
for_in_array()
println('')
for_in_map()
}
BASIC
BaCon
BaCon includes support for delimited strings. Delimited strings form a type of collection. Along with this support is a for in
loop. Not quite a for each
but pretty close.
OPTION COLLAPSE TRUE
FOR x$ IN "Hello cruel world"
PRINT x$
NEXT
FOR y$ IN "1,2,\"3,4\",5" STEP ","
PRINT y$
NEXT
- Output:
prompt$ bacon -q forin.bac >/dev/null prompt$ ./forin Hello cruel world 1 2 "3,4" 5
The OPTION COLLAPSE TRUE
statements prevents empty results when multiple delimiters appear together. The default delimiter is space, and can be changed with OPTION DELIM x
where x is a static string literal.
BASIC256
BASIC-256 does not have a FOR EACH type statement. Use a FOR loop to iterate through an array by index.
DIM collection$(1)
collection$ = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }
FOR i = 0 TO collection$[?]-1
PRINT collection$[i]+ " ";
NEXT i
PRINT
Output:
The quick brown fox jumps over the lazy dog.
BBC BASIC
DIM collection$(8)
collection$() = "The", "quick", "brown", "fox", "jumps", \
\ "over", "the", "lazy", "dog."
FOR index% = 0 TO DIM(collection$(), 1)
PRINT collection$(index%) " ";
NEXT
PRINT
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
10 DIM A$(9) :REM DECLARE STRING ARRAY
20 REM *** FILL ARRAY WITH WORDS ***
30 FOR I = 0 TO 8
40 READ A$(I)
50 NEXT
60 REM *** PRINT ARRAY CONTENTS ***
70 FOR I = 0 TO 8
80 PRINT A$(I)" ";
90 NEXT
100 END
1000 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.
Creative Basic
DEF AnArray[11]:INT
AnArray=0,1,2,3,4,5,6,7,8,9,10
'A console only program will work without OPENCONSOLE and
'CLOSECONSOLE; however, it does not hurt to use them.
OPENCONSOLE
FOR X=0 TO 10
PRINT AnArray[X]
NEXT X
'keep the console from closing right away.
DO:UNTIL INKEY$<>""
CLOSECONSOLE
'because this is a console only program.
END
FreeBASIC
' FB 1.05.0
' FreeBASIC doesn't have a foreach loop but it's easy to manufacture one using macros
#Macro ForEach(I, A)
For _i as integer = LBound(A) To UBound(A)
#Define I (A(_i))
#EndMacro
#Define In ,
Dim a(-5 To 5) As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
ForEach(i in a)
Print i; " ";
Next
Print
Sleep
- Output:
1 2 3 4 5 6 7 8 9 10 11
Gambas
Click this link to run this code
Public Sub Main()
Dim siInput As Short[] = [1, 8, 0, 6, 4, 7, 3, 2, 5, 9]
Dim siTemp As Short
For Each siTemp In siInput.Sort()
Print siTemp;;
Next
End
- Output:
0 1 2 3 4 5 6 7 8 9
IS-BASIC
100 STRING COLLECTION$(1 TO 9)*8
110 LET I=1
120 DO
130 READ IF MISSING EXIT DO:COLLECTION$(I)
140 LET I=I+1
150 LOOP
160 FOR J=1 TO I-1
170 PRINT COLLECTION$(J);" ";
180 NEXT
190 DATA The,quick,brown,fox,jumps,over,the,lazy,dog.
IWBASIC
Linked List
DEF AList:POINTER
AList=ListCreate()
'Add items to the list.
DEF X:INT
FOR X=0 TO 10
POINTER Temp=ListAdd(AList,NEW(INT,1))
#<INT>temp=X
'The hash ("#") dereferencing operator is unique to IWBASIC and Creative Basic, and
'it is suitable for most basic pointer needs. IWBASIC also supports a "C style"
'dereferencing operator: "*". And that will work here too.
NEXT X
'A program compiled as console only does not need the commands to open and
'close the console. However, it does not hurt to use them.
OPENCONSOLE
'***Iterate the list with the "for each" loop***
FOR Temp=EACH AList AS INT
PRINT #Temp
NEXT
PRINT
'A press any key to continue message is automatic in a program compiled as a console only
program. I presume the compiler inserts the code.
CLOSECONSOLE
'Because this is a console only program.
END
An Array
DEF AnArray[11]:INT
AnArray=0,1,2,3,4,5,6,7,8,9,10
OPENCONSOLE
FOR X=0 TO 10
PRINT AnArray[X]
NEXT X
PRINT
'a press any key message is automatic when compiled as console only.
CLOSECONSOLE
'Because this is a console only program.
END
Lambdatalk
{def collection alpha beta gamma delta}
-> collection
{S.map {lambda {:i} {br}:i} {collection}}
->
alpha
beta
gamma
delta
or
{def S.foreach
{lambda {:s}
{if {S.empty? {S.rest :s}}
then {S.first :s}
else {S.first :s} {br}{S.foreach {S.rest :s}}}}}
{S.foreach {collection}}
->
alpha
beta
gamma
delta
Liberty BASIC
The most natural way is to use a csv list with a sentinel value.
in$ ="Not,Hardly,Just,Adequately,Quite,Really,Very,Fantastically,xyzzy"
element$ =""
i =1 ' used to point to successive elements
do
element$ =word$( in$, i, ",")
if element$ ="xyzzy" then exit do
print element$; " good!"
i =i +1
loop until 1 =2
end
Not good! Hardly good! Just good! Adequately good! Quite good! Really good! Very good! Fantastically good!
NS-HUBASIC
10 DIM A$(9) : REM DECLARE STRING ARRAY
20 REM ADD DATA TO ARRAY AND PRINT ARRAY CONTENTS
30 FOR I=0 TO 8
40 READ A$(I)
50 PRINT A$(I)" ";
60 NEXT
70 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.
PureBasic
Works for LinkedLists and Maps
ForEach element()
PrintN(element())
Next
Run BASIC
t$={Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday"
while word$(t$,i+1,",") <> ""
i = i + 1
print word$(t$,i,",")
wend
TI-89 BASIC
Local i,strs
Define strs = {"Lorem","ipsum","dolor"}
For i, 1, dim(strs)
Disp strs[i]
EndFor
VBA
Public Sub LoopsForeach()
Dim FruitArray() As Variant
Dim Fruit As Variant
FruitArray = [{"Apple","Banana","Strawberry"}]
Dim FruitBasket As Collection
Set FruitBasket = New Collection
For Each Fruit In FruitArray
FruitBasket.Add Fruit
Next Fruit
For Each Fruit In FruitBasket
Debug.Print Fruit
Next Fruit
End Sub
VBScript
items = Array("Apple", "Orange", "Banana")
For Each x In items
WScript.Echo x
Next
Visual Basic .NET
Dim list As New List(Of String)
list.Add("Car")
list.Add("Boat")
list.Add("Train")
For Each item In list
Console.WriteLine(item)
Next
Yabasic
//Yabasic tampoco tiene una construcción ForEach.
//Mediante un bucle FOR iteramos a través de una matriz por índice.
//READ-DATA se usa para rellenar la matriz
dim arreglo(10)
data 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
for each = 0 to arraysize(a(),1)
read arreglo(each)
next each
for each = 0 to arraysize(a(),1)
print arreglo(each), " ";
next each
print
end
Batch File
The FOR command can imitate the "Foreach Loop". The whitespace and the comma (,) are the default delimiters.
Direct usage:
@echo off
for %%A in (This is a sample collection) do (
echo %%A
)
Using a Collection Variable:
@echo off
set "collection=This is a sample collection"
for %%A in (%collection%) do (
echo %%A
)
- They have the Same Output:
This is a sample collection
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.
a[0] = .123
a[1] = 234
a[3] = 95.6
for (i = 0; i < 4; i++) {
a[i]
}
Bracmat
Bracmat has a more or less traditional 'while' loop (whl'expression
) 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:
( list
= Afrikaans
Ελληνικά
עברית
മലയാളം
ئۇيغۇرچە
)
The 'while' solution. Use an auxiliary variable L
that gets its head chopped off until nothing is left:
!list:?L
& whl'(!L:%?language ?L&out$!language)
The tail-recursive solution. When the auxiliary variable is reduced to nothing, the loop fails. By adding the ~
flag to the initial invocation, failure is turned into success. This solution benefits from tail recursion optimization.
!list:?L
& ( loop
= !L:%?language ?L
& out$!language
& !loop
)
& ~!loop
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 @
flag matches at most one element. The %
flag matches at least one element. Together they ensure that exactly one language name is assigned to the variable language
. After all elements have been done, control is passed to the rhs of the |
operator.
( !list
: ? (%@?language&out$!language&~) ?
|
)
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.
#include <stdio.h>
...
const char *list[] = {"Red","Green","Blue","Black","White"};
#define LIST_SIZE (sizeof(list)/sizeof(list[0]))
int ix;
for(ix=0; ix<LIST_SIZE; ix++) {
printf("%s\n", list[ix]);
}
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.
C string as a collection of char
#include <stdio.h>
#include <stdlib.h>
/* foreach macro for using a string as a collection of char */
#define foreach( ptrvar , strvar ) char* ptrvar; for( ptrvar=strvar ; (*ptrvar) != '\0' ; *ptrvar++)
int main(int argc,char* argv[]){
char* s1="abcdefg";
char* s2="123456789";
foreach( p1 , s1 ) {
printf("loop 1 %c\n",*p1);
}
foreach( p2 , s2 ){
printf("loop 2 %c\n",*p2);
}
exit(0);
return(0);
}
C int array as a collection of int (array size known at compile-time)
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char* argv[]){
/* foreach macro viewing an array of int values as a collection of int values */
#define foreach( intpvar , intary ) int* intpvar; for( intpvar=intary; intpvar < (intary+(sizeof(intary)/sizeof(intary[0]))) ; intpvar++)
int a1[]={ 1 , 1 , 2 , 3 , 5 , 8 };
int a2[]={ 3 , 1 , 4 , 1, 5, 9 };
foreach( p1 , a1 ) {
printf("loop 1 %d\n",*p1);
}
foreach( p2 , a2 ){
printf("loop 2 %d\n",*p2);
}
exit(0);
return(0);
}
Most general: string or array as collection (collection size known at run-time)
- Note: idxtype can be removed and typeof(col[0]) can be used in it's place with GCC
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char* argv[]){
#define foreach( idxtype , idxpvar , col , colsiz ) idxtype* idxpvar; for( idxpvar=col ; idxpvar < (col+(colsiz)) ; idxpvar++)
#define arraylen( ary ) ( sizeof(ary)/sizeof(ary[0]) )
char* c1="collection";
int c2[]={ 3 , 1 , 4 , 1, 5, 9 };
double* c3;
int c3len=4;
c3=(double*)calloc(c3len,sizeof(double));
c3[0]=1.2;c3[1]=3.4;c3[2]=5.6;c3[3]=7.8;
foreach( char,p1 , c1, strlen(c1) ) {
printf("loop 1 : %c\n",*p1);
}
foreach( int,p2 , c2, arraylen(c2) ){
printf("loop 2 : %d\n",*p2);
}
foreach( double,p3 , c3, c3len ){
printf("loop 3 : %3.1lf\n",*p3);
}
exit(0);
return(0);
}
C#
string[] things = {"Apple", "Banana", "Coconut"};
foreach (string thing in things)
{
Console.WriteLine(thing);
}
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 container_type and the actual container object is named container.
for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
std::cout << *i << "\n";
}
However the idiomatic way to output a container would be
std::copy(container.begin(), container.end(),
std::ostream_iterator<container_type::value_type>(std::cout, "\n"));
There's also an algorithm named for_each. However, you need a function or function object to use it, e.g.
void print_element(container_type::value_type const& v)
{
std::cout << v << "\n";
}
...
std::for_each(container.begin(), container.end(), print_element);
for (auto element: container)
{
std::cout << element << "\n";
}
Here container is the container variable, element 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:
for (auto const& element: container)
{
std::cout << element << "\n";
}
Of course the container elements can also be changed by using a non-const reference (provided the container isn't itself constant):
for (auto&& element: container) //use a 'universal reference'
{
element += 42;
}
C3
C3 has a standard built-in foreach for iterating through lists.
String[] fruits = { "Apple", "Banana", "Strawberry" };
foreach (fruit : fruits) io::printn(fruit);
Chapel
var food = ["Milk", "Bread", "Butter"];
for f in food do writeln(f);
Clojure
(doseq [item collection] (println item))
CLU
As in Python (which no doubt got the idea from CLU), every for loop in
CLU is really a foreach, and iterating over a range of numbers is done
by using an iterator (e.g. int$from_to
).
Unlike Python, the for loop only accepts iterators, and collections
are not automatically cast into iterators. To loop over the elements of an array,
one needs to explicitly use the elements
iterator.
start_up = proc ()
po: stream := stream$primary_output()
words: array[string] := array[string]$
["enemy", "lasagna", "robust", "below", "wax"]
for word: string in array[string]$elements(words) do
stream$putl(po, word)
end
end start_up
CMake
set(list one.c two.c three.c)
foreach(file ${list})
message(${file})
endforeach(file)
COBOL
The following is in the Managed COBOL dialect:
01 things occurs 3.
...
set content of things to ("Apple", "Banana", "Coconut")
perform varying thing as string through things
display thing
end-perform
ColdFusion
<Cfloop list="Fee, Fi, Foe, Fum" index="i">
<Cfoutput>#i#!</Cfoutput>
</Cfloop>
Common Lisp
(loop for i in list do (print i))
or
(map nil #'print list)
or
(dolist (x the-list) (print x))
or
(use-package :iterate)
(iter
(for x in the-list)
(print x))
Using DO
(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
((null i)) ; Break condition
(print (first i)))) ; On every loop print list's first element
- Output:
1 7 "foo" 1 4
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.
import std.stdio: writeln;
void main() {
auto collection1 = "ABC";
foreach (element; collection1)
writeln(element);
auto collection2 = [1, 2, 3];
foreach (element; collection1)
writeln(element);
auto collection3 = [1:10, 2:20, 3:30];
foreach (element; collection3)
writeln(element);
foreach (key, value; collection3)
writeln(key, " ", value);
}
- Output:
A B C A B C 10 20 30 1 10 2 20 3 30
Dao
items = { 1, 2, 3 }
for( item in items ) io.writeln( item )
Delphi
for..in loops were added in Delphi 2005.
Supports arrays (single, multidimensional, and dynamic), sets, strings, collections and any class or interface that implements GetEnumerator().
program LoopForEach;
{$APPTYPE CONSOLE}
var
s: string;
begin
for s in 'Hello' do
Writeln(s);
end.
Output:
H e l l o
Dragon
for value : array {
showln value
}
Dyalect
for i in [1,2,3] {
print(i)
}
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:
for i in [1,2,3].Iterate() {
print(i)
}
This would perfectly work with any custom iterator as well:
func myCollection() {
yield 1
yield 2
yield 3
}
for i in myCollection() {
print(i)
}
All three code samples would output:
1 2 3
E
for e in theCollection {
println(e)
}
In E, the for ... in ... loop is also used for iterating over numeric ranges; see Loop/For#E.
EasyLang
for i in [ 5 1 19 25 12 1 14 7 ]
print i
.
EchoLisp
(define my-list '( albert simon antoinette))
(for ((h my-list)) (write h))
albert simon antoinette
(define my-vector #(55 66 soixante-dix-sept))
(for (( u my-vector)) (write u))
55 66 soixante-dix-sept
(define my-string "Longtemps")
(for ((une-lettre my-string)) (write une-lettre))
"L" "o" "n" "g" "t" "e" "m" "p" "s"
;; etc ... for other collections like Streams, Hashes, Graphs, ...
Ecstasy
module LoopForEach {
@Inject Console console;
void run() {
val vals = [10, 20, 30, 40];
console.print("Array of values:");
Loop: for (val val : vals) {
console.print($" value #{Loop.count + 1}: {val}");
}
Map<String, Int> pairs = ["x"=42, "y"=69];
console.print("\nKeys and values:");
for ((String key, Int val) : pairs) {
console.print($" {key}={val}");
}
console.print("\nJust the keys:");
Loop: for (String key : pairs) {
console.print($" key #{Loop.count + 1}: {key}");
}
console.print("\nValues from a range:");
for (Int n : 1..5) {
console.print($" {n}");
}
}
}
- Output:
Array of values: value #1: 10 value #2: 20 value #3: 30 value #4: 40 Keys and values: x=42 y=69 Just the keys: key #1: x key #2: y Values from a range: 1 2 3 4 5
Ed
Print all (newline-separated) lines in the file.
,p
Efene
Any data structure can be printed as a whole, preformated:
io.format("~p~n", [Collection])
However, to iterate over each element of a list, Efene uses lists.map/2, except in the case of IO where lists.foreach/2 has to be used as the evaluation order is defined to be the same as the order of the elements in the list.
lists.foreach(fn (X) { io.format("~p~n", [X]) }, Collection)
Eiffel
The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword across
.
across my_list as ic loop print (ic.item) end
The local entity ic
is an instance of the library class ITERATION_CURSOR
. The cursor's feature item
provides access to each structure element. Descendants of class ITERATION_CURSOR
can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (my_list
in the example) are based on classes that inherit from the library class ITERABLE
Boolean expression variant
The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword loop
is replaced by either all
(effecting universal quantification) or some
(effecting existential quantification).
This iteration is a boolean expression which is true if all items in my_list
have counts greater than three:
across my_list as ic all ic.item.count > 3 end
Whereas, the following is true if at least one item has a count greater than three:
across my_list as ic some ic.item.count > 3 end
Ela
open monad io
each [] = do return ()
each (x::xs) = do
putStrLn $ show x
each xs
Elena
ELENA 6.x :
import system'routines;
import extensions;
public program()
{
var things := new string[]{"Apple", "Banana", "Coconut"};
things.forEach::(thing)
{
console.printLine(thing)
}
}
Using foreach statement template
import extensions;
public program()
{
var things := new string[]{"Apple", "Banana", "Coconut"};
foreach(var thing; in things)
{
console.printLine(thing)
}
}
Elixir
iex(1)> list = [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)
1
3.14
"abc"
[3]
{0, 5}
:ok
Emacs Lisp
For a list either dolist
macro
(dolist (x '(1 2 3 4))
(message "x=%d" x))
or mapc
function
(mapc (lambda (x)
(message "x=%d" x))
'(1 2 3 4))
(cl-loop for x in '(1 2 3 4) do (message "x=%d" x))
Erlang
Any data structure can be printed as a whole, preformated:
io:format("~p~n",[Collection]).
However, to iterate over each element of a list, Erlang uses lists:map/2, except in the case of IO where lists:foreach/2 has to be used as the evaluation order is defined to be the same as the order of the elements in the list.
lists:foreach(fun(X) -> io:format("~p~n",[X]) end, Collection).
ERRE
It's an extension of 'standard' FOR loop: constant list must be explicit.
FOR INDEX$=("The","quick","brown","fox","jumps","over","the","lazy","dog.") DO
PRINT(INDEX$;" ";)
END FOR
PRINT
Euphoria
include std/console.e
sequence s = {-2,-1,0,1,2} --print elements of a numerical list
for i = 1 to length(s) do
? s[i]
end for
puts(1,'\n')
s = {"Name","Date","Field1","Field2"} -- print elements of a list of 'strings'
for i = 1 to length(s) do
printf(1,"%s\n",{s[i]})
end for
puts(1,'\n')
for i = 1 to length(s) do -- print subelements of elements of a list of 'strings'
for j = 1 to length(s[i]) do
printf(1,"%s\n",s[i][j])
end for
puts(1,'\n')
end for
if getc(0) then end if
- Output:
-2 -1 0 1 2 Name Date Field1 Field2 N a m e D a t e F i e l d 1 F i e l d 2
F#
We can use for directly or list iteration.
for i in [1 .. 10] do printfn "%d" i
List.iter (fun i -> printfn "%d" i) [1 .. 10]
Factor
{ 1 2 4 } [ . ] each
Fantom
Use each
method to iterate over a collection of items in a List
.
class Main
{
public static Void main ()
{
Int[] collection := [1, 2, 3, 4, 5]
collection.each |Int item|
{
echo (item)
}
}
}
Fennel
sequential table
(each [k v (ipairs [:apple :banana :orange])]
(print k v))
- Output:
1 apple 2 banana 3 orange
key-value table
(each [k v (pairs {:apple :x :banana 4 :orange 3})]
(print k v))
- Output:
apple x banana 4 orange 3
Forth
create a 3 , 2 , 1 ,
: .array ( a len -- )
cells bounds do i @ . cell +loop ; \ 3 2 1
FOREACH
The thing about extensible languages is if you need FOREACH, you can have FOREACH. The Forth ' operator returns the "execution token" (XT) of a Forth word. An XT can be run with EXECUTE. If we apply an appropriate XT to all the elements of an array we have it.
: FOREACH ( array size XT --)
>R \ save execution token on return stack
CELLS BOUNDS \ convert addr,len -> last,first addresses
BEGIN
2DUP > \ test addresses
WHILE ( last>first )
DUP R@ EXECUTE \ apply the execution token to the address
CELL+ \ move first to the next memory cell
REPEAT
R> DROP \ clean return stack
2DROP \ and data stack
;
\ Make an operator to fetch contents of an address and print
: ? ( addr --) @ . ;
CREATE A[] 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ,
\ Usage example:
A[] 10 ' ? FOREACH
Fortran
program main
implicit none
integer :: i
character(len=5),dimension(5),parameter :: colors = ['Red ','Green','Blue ','Black','White']
!using a do loop:
do i=1,size(colors)
write(*,'(A)') colors(i)
end do
!this will also print each element:
write(*,'(A)') colors
end program main
friendly interactive shell
Unlike, bash or csh, the PATH variable is automatically converted to real array.
for path in $PATH
echo You have $path in PATH.
end
Sample output:
You have /bin in PATH. You have /usr/bin in PATH.
Frink
Frink's for
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.
array = [1, 2, 3, 5, 7]
for n = array
println[n]
FutureBasic
window 1
void local fn DoIt
CFArrayRef array = @[@"Alpha",@"Bravo",@"Charlie",@"Delta",@"Echo",@"FutureBasic"]
CFStringRef string
for string in array
print string
next
end fn
fn DoIt
HandleEvents
- Output:
Alpha Bravo Charlie Delta Echo FutureBasic
GAP
for p in AlternatingGroup(4) do
Print(p, "\n");
od;
()
(1,3,2)
(1,2,3)
(1,4,3)
(2,4,3)
(1,3)(2,4)
(1,2,4)
(1,4)(2,3)
(2,3,4)
(1,3,4)
(1,2)(3,4)
(1,4,2)
Go
range
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.
func printAll(values []int) {
for i, x := range values {
fmt.Printf("Item %d = %d\n", i, x)
}
}
Groovy
"for" loop:
def beatles = ["John", "Paul", "George", "Ringo"]
for(name in beatles) {
println name
}
"each()" method:
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.
beatles.each {
println it
}
Output (same for either):
John Paul George Ringo
Halon
$things = ["Apple", "Banana", "Coconut"];
foreach ($things as $thing) {
echo $thing;
}
Haskell
import Control.Monad (forM_)
forM_ collect print
which is the same as
mapM_ print collect
Haxe
var a = [1, 2, 3, 4];
for (i in a)
Sys.println(i);
HicEst
CHARACTER days="Monday Tuesday Wednesday Thursday Friday Saturday Sunday "
items = INDEX(days, ' ', 256) ! 256 = count option
DO j = 1, items
EDIT(Text=days, ITeM=j, Parse=today)
WRITE() today
ENDDO
Hy
(for [x collection] (print x))
Icon and Unicon
The example below X can be a list, string, table or other data type.
This loop can be written somewhat more concisely as:
Io
collection foreach(println)
J
echo every i.10
0
1
2
3
4
5
6
7
8
9
That said, J's for.
provides a "foreach" mechanism.
{{for_i. i. y do. echo i end.}}10
0
1
2
3
4
5
6
7
8
9
Java
Iterable<Type> collect;
...
for(Type i:collect){
System.out.println(i);
}
This works for any array type as well as any type that implements the Iterable interface (including all Collections).
Iterable collect;
...
collect.forEach(o -> System.out.println(o));
This works with any Iterable, but not with arrays.
JavaScript
For arrays in ES5, we can use Array.forEach():
"alpha beta gamma delta".split(" ").forEach(function (x) {
console.log(x);
});
though it will probably be more natural – dispensing with side-effects, and allowing for easier composition of nested functions – to simply use Array.map(),
console.log("alpha beta gamma delta".split(" ").map(function (x) {
return x.toUpperCase(x);
}).join("\n"));
or, more flexibly, and with greater generality, obtain an accumulating fold from Array.reduce()
console.log("alpha beta gamma delta".split(" ").reduce(function (a, x, i, lst) {
return lst.length - i + ". " + x + "\n" + a;
}, ""));
More generally, the following works for any object, including an array. It iterates over the keys of an object.
for (var a in o) {
print(o[a]);
}
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:
for (var a in o) {
if (o.hasOwnProperty(a)) {
print(o[a]);
}
}
- Deprecated
There is also a for each in construct that iterates over the values of an object:
h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for each (y in h) print(y);
There is also a for of construct that iterates over the values of an object:
h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for (y of h) print(y);
jq
Iterables:
In this section, the array defined by "example" is used as an example:
def example: [1,2];
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:
example | .[]
# or equivalently: example[]
{"a":1, "b":2} | .[]
# or equivalently: {"a":1, "b":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:
example | . as $a | range(0; length) | $a[.]
For JSON objects, the corresponding technique involves using keys, e.g.
{"a":1, "b":2} | . as $o | keys | map( [., $o[.]] )
produces:
[["a",1],["b",2]]
Strings:
To convert the constituent characters (or technically, codepoints) of a string into a stream of values, there are two techniques illustrated by these examples:
"abc" | . as $s | range(0;length) | $s[.:.+1]
"abc" | explode | map( [.]|implode) | .[]
In both cases, the result is the stream of values: "a", "b", "c".
Jsish
Jsi supports for of for looping over element of an array.
for (str of "alpha beta gamma delta".split(' ')) { puts(str); }
- Output:
alpha beta gamma delta
Julia
for i in collection
println(i)
end
The Julia for
statement is always a "foreach", and the built-in start:end
or start:step:end
"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.
K
{`0:$x} ' !10
_sin ' (1; 2; 3;)
Klingphix
include ..\Utilitys.tlhy
( -2 "field" 3.14159 ( "this" "that" ) ) len [get ?] for
" " input
- Output:
-2 field 3.14159 ("this", "that")
Kotlin
// version 1.0.6
fun main(args: Array<String>) {
val greek = arrayOf("alpha", "beta", "gamma", "delta")
for (letter in greek) print("$letter ")
println()
// or alternatively
greek.forEach { print("$it ") }
println()
}
- Output:
alpha beta gamma delta alpha beta gamma delta
LabVIEW
LabVIEW has a feature known as an Auto-Indexed Tunnel. It is the very small orange box on the lower left of the for loop.
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lambdatalk
{def collection alpha beta gamma delta}
-> collection
{S.map {lambda {:i} {br}:i} {collection}}
->
alpha
beta
gamma
delta
or
{def S.foreach
{lambda {:s}
{if {S.empty? {S.rest :s}}
then {S.first :s}
else {S.first :s} {br}{S.foreach {S.rest :s}}}}}
{S.foreach {collection}}
->
alpha
beta
gamma
delta
Lang
$collection = fn.arrayOf(1, 2, 3)
# Foreach loop [Works with iterable types (text, collections [array, list])]
$ele
foreach($[ele], $collection) {
fn.println($ele)
}
# Foreach function
# Array: fn.arrayForEach(&arr, func)
# List: fn.listForEach(&list, func)
fn.arrayForEach($collection, fn.println)
Lang5
: >>say.(*) . ;
5 iota >>say.
langur
A for in loop iterates over values and a for of loop iterates over keys.
for i in [1, 2, 3] {
writeln i
}
val abc = "abc"
for i in abc {
writeln i
}
for i of abc {
writeln abc[i]
}
for i in abc {
writeln cp2s(i)
}
- Output:
1 2 3 97 98 99 97 98 99 a b c
Lasso
array(1,2,3) => foreach { stdoutnl(#1) }
with i in array(1,2,3) do { stdoutnl(#i) }
LDPL
data:
fruits is text list
fruit is text
procedure:
split "apple banana orange" by " " in fruits
for each fruit in fruits do
display fruit lf
repeat
- Output:
apple banana orange
LFE
(lists:foreach
(lambda (x)
(io:format "item: ~p~n" (list x)))
(lists:seq 1 10))
LIL
# Loops/Foreach, in LIL
set collection [list 1 2 "three"]
append collection [list 4 5 six] # appended as a single item in collection
print "Collection is: $collection"
# using default "i" variable name set for each item
foreach $collection {print $i}
# user named variable in the steps, retrieving accumulated result of loop
# each loop step quotes two copies of the item
set newlist [foreach j $collection {quote $j $j}]
print "Result of second foreach: $newlist"
- Output:
prompt$ lil loopsForeach.lil Collection is: 1 2 three {4 5 six} 1 2 three 4 5 six Result of second foreach: {1 1} {2 2} {three three} {4 5 six 4 5 six}
Lingo
days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
repeat with day in days
put day
end repeat
A callback-based forEach() can be implemented like this:
----------------------------------------
-- One of the five native iterative methods defined in ECMAScript 5
-- @param {list} tList
-- @param {symbol} cbFunc
-- @param {object} [cbObj=_movie]
----------------------------------------
on forEach (tList, cbFunc, cbObj)
if voidP(cbObj) then cbObj = _movie
cnt = tList.count
repeat with i = 1 to cnt
call(cbFunc, cbObj, tList[i], i, tList)
end repeat
end
days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
forEach(days, #alert, _player)
Lisaac
"Lisaac loop foreach".split.foreach { word : STRING;
word.print;
'\n'.print;
};
LiveCode
Livecode's for each operates on chunks which may be words, items, lines, tokens. Example is for items.
repeat for each item x in "red, green, blue"
put x & cr
--wait 100 millisec -- req'd if you want to see in the LC Message Box (akin to repl)
end repeat
Logo
foreach [red green blue] [print ?]
Lua
Lua has 2 built-in iterators over tables.
pairs()
iterates over all entries in a table, but in no particular order:
t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"}
for key, value in pairs(t) do
print(value, key)
end
Output:
0 sunday fooday 7 2 tuesday 3 wednesday 5 friday 4 thursday 6 saturday 1 monday
ipairs()
iterates over table entries with positive integer keys,
and is used to iterate over lists in order.
l={'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', not_a_number='fooday', [0]='today', [-1]='yesterday' }
for key, value in ipairs(l) do
print(key, value)
end
Output:
1 monday 2 tuesday 3 wednesday 4 thursday 5 friday 6 saturday 7 sunday
Note that ipairs()
ignores non-numeric and non-positive integer keys.
M2000 Interpreter
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.
Module Checkit {
\\ Inventories may have keys or keys/values
\\ here keys are values too
Inventory Alfa="Apple", "Banana", "Coconut"
\\ key 30 has value 25, other keys have value same as key.
Inventory Beta=100, 30:=25, 20, 5
Print "Parallel"
k=Each(Alfa)
k1=Each(Alfa End to Start)
k2=Each(Beta)
\\ Parallel iterators
\\ when one of them end then while end too.
\\ so 5 not printed. Print 100, 25, 20
While k,k2, k1 {
Print Eval$(k), Eval$(k1), Eval(k2)
}
Print "Nested"
\\ Nested iterators
k=Each(Alfa)
While k {
k1=Each(Alfa End to Start)
While k1 {
Print Eval$(k), Eval$(k1)
}
}
}
Checkit
Maple
for p in [2, 3, 5, 7] do
print(p);
end do;
Mathematica/Wolfram Language
Foreach over list of strings
s = (StringSplit@Import["ExampleData/USConstitution.txt"])[[1;;7]];
Do[
Print@i,
{i, s}
]
Output:
We the People of the United States,
MATLAB / Octave
list1 = [1,5,6,7,-7,-9];
for k = list1, % list1 must be a row vector (i.e. array of size 1xn)
printf('%i\n',k)
end;
list2 = {'AA','BB','CC'};
for k = list2, % list2 must be a row vector (i.e. array of size 1xn)
printf('%s\n',k{1})
end;
A vectorized version of the code is
printf('%d\n',list1);
printf('%s\n',list2{:});
Maxima
for n in [2, 3, 5, 7] do print(n);
MAXScript
arr = for i in 1 to 50 collect ("Number: " + (random 10 99) as string)
makeuniquearray arr
sort arr
for i in arr do print i as string
Metafont
If we have a list of arbitrary items, we can simply use for:
for x = "mary", "had", "a", "little", "lamb": message x; endfor
end
The list can be generated in place by any suitable macro or another loop... e.g. let us suppose we have things like a[n] defined (with maximum n being 10). Then
for x = for i = 1 upto 9: a[i], endfor, a[10]: show x; endfor
end
works more like a foreach; we could make a macro to hide the strangeness of such a code.
min
(1 2 3) 'puts foreach
MiniScript
for i in collection
print i
end
The MiniScript for
statement is always a "foreach", and the standard range
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.
MOO
things = {"Apple", "Banana", "Coconut"};
for thing in (things)
player:tell(thing);
endfor
Nanoquery
Like Python, Nanoquery supports for...in syntax for list types and strings.
for item in collection
println item
end
Some examples:
for n in {1,3,5,7,9}
print n + " "
end
println
for char in "test string"
print char
end
println
- Output:
1 3 5 7 9 test string
Nemerle
This works on anything which implements the IEnumerable interface.
def things = ["Apple", "Banana", "Coconut"];
foreach (thing in things) WriteLine(thing.ToLower());
foreach (i in [5, 10 .. 100]) Write($"$i\t");
NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
say
say 'Loops/Foreach'
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
daysl = Arrays.asList(days)
daysi = daysl.iterator
loop while daysi.hasNext
say daysi.next
end
NewLISP
(map println '(Apple Banana Coconut))
Nim
let list = ["lorem", "ipsum", "dolor"]
for item in list:
echo item
- Output:
lorem ipsum dolor
Nu
let l = [a b c d]
for x in $l {print $x}
- Output:
a b c d
Objeck
fruits := ["Apple", "Banana", "Coconut"];
each(i : fruits) {
fruits[i]->PrintLine();
};
Objective-C
NSArray *collect;
// ...
for (Type i in collect) {
NSLog(@"%@", i);
}
collect can be any object that adopts the NSFastEnumeration protocol.
Or (always using OpenStep compatible frameworks):
NSArray *collect;
// ...
NSEnumerator *enm = [collect objectEnumerator];
id i;
while ((i = [enm nextObject])) {
// do something with object i
}
OCaml
List of integers:
List.iter
(fun i -> Printf.printf "%d\n" i)
collect_list
Array of integers:
Array.iter
(fun i -> Printf.printf "%d\n" i)
collect_array
Octave
a = [ 1,4,3,2 ];
b = [ 1,2,3,4; 5,6,7,8 ];
for v = a
disp(v); % output single values: 1,4,3,2
endfor
for v = b
disp(v); % v is the column vector [1;5], then [2;6] ...
endfor
We can also iterate over structures:
x.a = [ 10, 11, 12 ];
x.b = { "Cell", "ul", "ar" };
for [ val, key ] = x
disp(key);
disp(val);
endfor
Oforth
: printMonths | m | Date.Months forEach: m [ m . ] ;
But, apply can be used instead of a loop :
#. Date.Months apply
Ol
(for-each print '(1 3 4 2))
(print)
(for-each (lambda (a b c) (print a "-" b "/" c))
'(1 2 3 4)
'(5 6 7 8)
'(a b x z))
- Output:
1 3 4 2 1-5/a 2-6/b 3-7/x 4-8/z
ooRexx
The OVER loop control keyword is used to select each item in a collection in turn. Open Object Rexx allows the DO block structure keyword to be used to start a loop for backward compatibility with classic Rexx; the LOOP keyword is preferred here as it is self-documenting.
/* Rexx */
say
say 'Loops/Foreach'
out = ''
days = .array~of('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
loop daysi over days
out ||= daysi' '
end daysi
say out~strip()
exit
Output:
Loops/Foreach Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Oz
declare
MyList = [1 2 3 4]
in
{ForAll MyList Show}
%% or:
for E in MyList do {Show E} end
PARI/GP
for(i=1,#v,print(v[i]))
or (PARI/GP >= 2.4)
apply(x->print(x),v)
Pascal
See Delphi
PascalABC.NET
##
foreach var s in |'Pascal','ABC','.NET'| do
Print(s);
Perl
foreach my $i (@collection) {
print "$i\n";
}
The keyword for
can be used instead of foreach
. If a loop variable (here $i
) is not given, then $_
is used.
A more compact notation using perl statement modifier:
print "$_\n" foreach @collection
In perl, it is possible to loop against an explicit list, so there is no need to define a container:
foreach $l ( "apples", "bananas", "cherries" ) {
print "I like $l\n";
}
Phix
sequence s = {-2,"field",3.14159268979,{"this","that"}} for i=1 to length(s) do ?s[i] end for
PHL
var numbers = 1..10;
numbers each # (number) [
printf("%i\n", number);
];
PHP
foreach ($collect as $i) {
echo "$i\n";
}
foreach ($collect as $key => $i) {
echo "\$collect[$key] = $i\n";
}
foreach
can also iterate over objects. By default it iterates over all visible fields of an object.
PicoLisp
(mapc println '(Apple Banana Coconut))
Pike
int main(){
array(int|string) collect = ({109, "Hi", "asdf", "qwerty"});
foreach(collect, int|string elem){
write(elem + "\n");
}
}
Iterating over the keys and values of a mapping (dictionary):
int main(){
mapping(string:string) coll = (["foo":"asdf", "bar":"qwer", "quux":"zxcv"]);
foreach (coll;string key;string val)
write(key+" --> "+val+"\n");
}
}
PL/I
declare A(10) fixed binary;
do i = lbound(A,1) to hbound(A,1);
put skip list (A(i));
end;
Plain English
To run:
Start up.
Create a list.
Write each entry in the list to the console.
Destroy the list.
Wait for the escape key.
Shut down.
An entry is a thing with a number.
A list is some entries.
To add a number to a list:
Allocate memory for an entry.
Put the number into the entry's number.
Append the entry to the list.
To create a list:
Add 1 to the list.
Add 2 to the list.
Add 3 to the list.
Add 6 to the list.
Add 7 to the list.
Add 9 to the list.
To write an entry to the console:
Convert the entry's number to a string.
Write the string to the console.
To write each entry in a list to the console:
Get an entry from the list.
Loop.
If the entry is nil, exit.
Write the entry to the console.
Put the entry's next into the entry.
Repeat.
- Output:
1 2 3 6 7 9
Pop11
Iteration over list:
lvars el, lst = [1 2 3 4 foo bar];
for el in lst do
printf(el,'%p\n');
endfor;
PostScript
The forall
operator performs a loop over a collection (array, string or dictionary). Strings and arrays can be treated very much the same:
[1 5 3 2] { = } forall
(abc) { = } forall
but dictionaries take a little more work since a key/value pair is pushed on the stack in each iteration:
<</a 25 /b 42>> {
exch (Key: ) print
=
(Value: ) print
=
} forall
PowerShell
$colors = "Black","Blue","Cyan","Gray","Green","Magenta","Red","White","Yellow",
"DarkBlue","DarkCyan","DarkGray","DarkGreen","DarkMagenta","DarkRed","DarkYellow"
foreach ($color in $colors)
{
Write-Host "$color" -ForegroundColor $color
}
- Output:
Black Blue Cyan Gray Green Magenta Red White Yellow DarkBlue DarkCyan DarkGray DarkGreen DarkMagenta DarkRed DarkYellow
Prolog
For example :
?- foreach(member(X, [red,green,blue,black,white]), writeln(X)).
red
green
blue
black
white
true.
Python
for i in collection:
print i
Note: The Python for
statement is always a "foreach" ... and the range()
and xrange()
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:
lines = words = characters = 0
f = open('somefile','r')
for eachline in f:
lines += 1
for eachword in eachline.split():
words += 1
for eachchar in eachword:
characters += 1
print lines, words, characters
Whether for
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.
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 sorted()
), whereas in Python 2.x numeric types are sorted according to their string representation by default:
d = {3: "Earth", 1: "Mercury", 4: "Mars", 2: "Venus"}
for k in sorted(d):
print("%i: %s" % (k, d[k]))
d = {"London": "United Kingdom", "Berlin": "Germany", "Rome": "Italy", "Paris": "France"}
for k in sorted(d):
print("%s: %s" % (k, d[k]))
d = {"fortytwo": 42, 3.14159: "pi", 23: "twentythree", "zero": 0, 13: "thirteen"}
for k in sorted(d):
print("%s: %s" % (k, d[k]))
Quackery
$ "Sweet Boom Pungent Prickle Orange" nest$
witheach [ i times sp echo$ cr ]
- Output:
Sweet Boom Pungent Prickle Orange
R
a <- list("First", "Second", "Third", 5, 6)
for(i in a) print(i)
Racket
#lang racket
;; an example sequence
(define sequence '("something" 1 2 "foo"))
;; works for any sequence
(for ([i sequence])
(displayln i))
Raku
(formerly Perl 6)
say $_ for @collection;
Raku leaves off the each from foreach, leaving us with for instead. The variable $_ refers to the current element, unless you assign a name to it using ->.
for @collection -> $currentElement { say $currentElement; }
Raku will do it's best to put the topic at the right spot.
.say for @collection;
for @collection { .say };
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.
@collection>>.say;
@collection>>.=&infix:<+>(2); # increment each element by 2
REBOL
REBOL [
Title: "Loop/Foreach"
URL: http://rosettacode.org/wiki/Loop/Foreach
]
x: [Sork Gun Blues Neds Thirst Fright Catur]
foreach i x [prin rejoin [i "day "]] print ""
; REBOL also has the 'forall' construct, which provides the rest of
; the list from the current position.
forall x [prin rejoin [x/1 "day "]] print ""
Output:
Sorkday Gunday Bluesday Nedsday Thirstday Frightday Caturday Sorkday Gunday Bluesday Nedsday Thirstday Frightday Caturday
Red
>> blk: ["John" 23 "dave" 30 "bob" 20 "Jeff" 40]
>> foreach item blk [print item]
John
23
dave
30
bob
20
Jeff
40
>> foreach [name age] blk [print [name "is" age "years old"]]
John is 23 years old
dave is 30 years old
bob is 20 years old
Jeff is 40 years old
>> forall blk [print blk]
John 23 dave 30 bob 20 Jeff 40
23 dave 30 bob 20 Jeff 40
dave 30 bob 20 Jeff 40
30 bob 20 Jeff 40
bob 20 Jeff 40
20 Jeff 40
Jeff 40
40
ReScript
let fruits = ["apple", "banana", "coconut"]
Js.Array2.forEach(fruits, f => Js.log(f))
Retro
Retro has for-each combinators for operating on elements of various data structures.
# Strings
This will display the ASCII code for each character in a string
~~~
'This_is_a_message [ n:put sp ] s:for-each
~~~
# Array
Display each element
~~~
{ #1 #2 #3 } [ n:put sp ] a:for-each
~~~
# Linked List
Using the dictionary as an example, display each name
~~~
&Dictionary [ d:name s:put sp ] d:for-each
~~~
REXX
days = 'zuntik montik dinstik mitvokh donershtik fraytik shabes'
do j=1 for words(days) /*loop through days of the week. */
say word(days,j) /*display the weekday to screen. */
end /*j*/
/*stick a fork in it, we're done.*/
Ring
aList = "Welcome to the Ring Programming Language"
for n in aList
see n + nl
next
RPL
In RPL, « printing » a collection means sending it to the printer, if you have one. To just output the items of a list, you put them into the stack, like this:
≪ { "one" "two" "three" "four" "five" } LIST→ DROP ≫
If the idea is to do more than displaying the items, the usual way is a FOR..NEXT
loop
≪ { "one" "two" "three" "four" "five" } → collection ≪ 1 collection SIZE FOR j collection j GET (do something with the item here) NEXT ≫ ≫
Ruby
for i in collection do
puts i
end
This is syntactic sugar for:
collection.each do |i|
puts i
end
There are various flavours of each
that may be class-dependent: String#each_char, Array#each_index, Hash#each_key, etc
Rust
Rust's for-loop already is a foreach-loop.
let collection = vec![1,2,3,4,5];
for elem in collection {
println!("{}", elem);
}
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.
let mut collection = vec![1,2,3,4,5];
for mut_ref in &mut collection {
// alternatively:
// for mut_ref in collection.iter_mut() {
*mut_ref *= 2;
println!("{}", *mut_ref);
}
// immutable borrow
for immut_ref in &collection {
// alternatively:
// for immut_ref in collection.iter() {
println!("{}", *immut_ref);
}
Since Rust 1.21 foreach can be used explicitly executing a closure on each element.
let collection = vec![1, 2, 3, 4, 5];
collection.iter().for_each(|elem| println!("{}", elem));
Salmon
iterate (x; ["Red", "Green", "Blue"])
x!;
output:
Red Green Blue
SAS
/* Initialize an array with integers 1 to 10, and print their sum */
data _null_;
array a a1-a10;
n=1;
do over a;
a=n;
n=n+1;
end;
s=sum(of a{*});
put s;
run;
Sather
class MAIN is
main is
num:ARRAY{INT} := |1, 5, 4, 3, 10|;
loop
-- the iterator elt! behaves like a "foreach",
-- yielding the next element of the array at each iteration
#OUT + num.elt! + "\n";
end;
end;
end;
Scala
val collection = Array(1, 2, 3, 4)
collection.foreach(println)
Alternatively:
(element <- 1 to 4).foreach(println)
Scheme
List:
(for-each
(lambda (i) (display i) (newline))
the_list)
Scilab
for e=["a","b","c"]
printf("%s\n",e)
end
- Output:
a b c
Seed7
The for loop of Seed7 can be used to loop over the elements of a container.
$ include "seed7_05.s7i";
var array string: things is [] ("Apple", "Banana", "Coconut");
const proc: main is func
local
var string: thing is "";
begin
for thing range things do
writeln(thing);
end for;
end func;
Self
aCollection do: [| :element | element printLine ].
(Provided that the objects in the collection understand the printLine
method).
SETL
S := {1,2,3,5,8,13,21,34,55,89};
for e in S loop
print(e);
end loop;
Sidef
foreach loop:
foreach [1,2,3] { |i|
say i
}
for-in loop:
for i in [1,2,3] {
say i
}
.each method:
[1,2,3].each { |i|
say i
}
Slate
c do: [| :obj | print: obj].
Smalltalk
aCollection do: [ :element | element displayNl ].
Provided that the objects in the collection understand the displayNl
method (which can be added, if missing).
Most modern Smalltalks allow for a selector symbol to be sent a value: message; which allows for the very compact:
aCollection do:#displayNl.
(and because Aikido mentions it: of course this works for any kind of collection (and even things which simply implement a do: method to iterate on something)
(1 to:6 by:2) do:#displayNl.
'hello' do:#displayNl.
(Integer primesUpTo:100) do:#displayNl.
'/' asFilename directoryContents do:#displayNl.
((Smalltalk allClasses collect:#name) asSortedCollection to:2) do:#displayNl.
funnyClassLessObject := Plug new
respondTo:#do:
with:[:arg |
arg value:'look ma'.
arg value:'no classes needed'].
funnyClassLessObject do:#displayNl.
etc.
- Output:
1 3 5 h e l l o 2 3 5 ... 97 home usr ... tmp cores AAAARecord AATree look ma no classes needed
Snabel
Prints foo, bar & baz followed by newlines.
['foo' 'bar' 'baz'] &say for
Sparkling
Sparkling currently has no "foreach" construct, but there's a "foreach" function in the standard library:
let hash = { "foo": 42, "bar": 1337, "baz": "qux" };
foreach(hash, function(key, val) {
print(key, " -> ", val);
});
Standard ML
List of integers:
app
(fn i => print (Int.toString i ^ "\n"))
collect_list
Array of integers:
Array.app
(fn i => print (Int.toString i ^ "\n"))
collect_array
Stata
local a 2 9 4 7 5 3 6 1 8
foreach i in `a' {
display "`i'"
}
Suneido
for i in #(1, 2, 3)
Print(i)
Swift
for i in [1,2,3] {
print(i)
}
This works for any type that conforms to the SequenceType
protocol (including arrays, collections, generators, ranges).
Alternately:
[1,2,3].forEach {
print($0)
}
SystemVerilog
program main;
int values[$];
initial begin
values = '{ 1, 3, 7, 11 };
foreach (values[i]) begin
$display( "%0d --> %0d", i, values[i] );
end
end
endprogram
Tailspin
Stream them
['a', 'b', 'c'] ... -> !OUT::write
- Output:
abc
Lists/arrays can be put through an array transform to get the index as well
['a', 'b', 'c'] -> \[i]('$i;:$;
' -> !OUT::write \) -> !VOID
- Output:
1:a 2:b 3:c
Tcl
foreach i {foo bar baz} {
puts "$i"
}
Note that foreach also accepts multiple variables:
foreach {x y} {1 2 3 4} {
puts "$x,$y"
}
And also multiple lists:
foreach i {1 2 3} j {a b c} {
puts "$i,$j"
}
Or any combination of variables/list:
foreach i {1 2 3} {x y} {a b c d e f} {
puts "$i,$x,$y"
}
Trith
[1 2 3 4 5] [print] each
TUSCRIPT
$$ MODE TUSCRIPT
week="Monday'Tuesday'Wednesday'Thursday'Friday'Saterday'Sunday"
LOOP day=week
PRINT day
ENDLOOP
Output:
Monday Tuesday Wednesday Thursday Friday Saterday Sunday
UNIX Shell
To iterate any single list, you use a for
loop.
for file in *.sh; do
echo "filename is $file"
done
If the list is in a shell parameter (like PATH
), you adjust IFS
.
PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin
oldifs=$IFS
IFS=:
for dir in $PATH; do
echo search $dir
done
IFS=$oldifs
Some shells have real arrays. The for
loop can also iterate these.
collection=("first" "second" "third" "fourth" "something else")
for x in "${collection[@]}"; do
echo "$x"
done
set -A collection "first" "second" "third" "fourth" "something else"
for x in "${collection[@]}"; do
echo "$x"
done
C Shell
set collection=(first second third fourth "something else")
foreach x ($collection:q)
echo $x:q
end
V
[1 2 3] [puts] step
Vala
List<string> things = new List<string> ();
things.append("Apple");
things.append("Banana");
things.append("Coconut");
foreach (string thing in things)
{
stdout.printf("%s\n", thing);
}
Vim Script
Vim Script's for-loop is actually a foreach-loop and iterates through a list.
for i in ["alpha", "beta", 42, 5.54]
echo i
endfor
V (Vlang)
fn print_all(values []int) {
for i, x in values {
println("Item $i = $x")
}
}
Wart
each x '(1 2 3)
prn x
WDTE
let a => import 'arrays';
let s => import 'stream';
a.stream [5; 7; 3]
-> s.map (io.writeln io.stdout)
-> s.drain
;
Wren
for (f in ["apples", "oranges", "pears"]) System.print(f)
- Output:
apples oranges pears
XLISP
XLISP's FOR-EACH applies a procedure to each member of a list in turn.
(FOR-EACH PRINT '(CYRUS CAMBYSES DARIUS XERXES ARTAXERXES))
- Output:
CYRUS CAMBYSES DARIUS XERXES ARTAXERXES
XPL0
Translation of C example:
include c:\cxpl\codes;
int List, I;
[List:= ["Red", "Green", "Blue", "Black", "White"];
for I:= 0, 5-1 do
[Text(0, List(I)); CrLf(0)];
]
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.
<fo:block font-weight="bold">Adults:</fo:block>
<xsl:for-each select="person[@age >= 21]">
<fo:block><xsl:value-of select="position()"/>. <xsl:value-of select="@name"/></fo:block>
</xsl:for-each>
zig
const warn = @import("std").debug.warn;
pub fn main() void {
const items = [_]i16{ 0, 1, 1, 2, 3, 5, 8 };
for (items) |i| {
warn("{}\n", .{i});
}
}
zkl
foreach c in (T("Red","Green","Blue","Black","White"))
{ print(c," "); }
- Output:
Red Green Blue Black White
Other forms of foreach, one that breaks apart a container into elements and one line nested loops.
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) }
- Output:
123 456
146 156 246 256 346 356
Zig
const std = @import("std");
pub fn main() !void {
const stdout_wr = std.io.getStdOut().writer();
// 1. Index element index sizes are comptime-known
const a1: []const u8 = &[_]u8{ 'a', 'b', 'c' };
// also works with slices
//const a2: [] u8 = &a1;
for (a1) |el_a|
try stdout_wr.print("{c}\n", .{el_a});
// 2. Index element index sizes are not comptime-known
// Convention is to provide a `next()` method.
// TODO
}
- Programming Tasks
- Iteration
- 11l
- ACL2
- Action!
- Ada
- Aikido
- Aime
- ALGOL 68
- Amazing Hopper
- AmigaE
- Apex
- AppleScript
- Arturo
- AutoHotkey
- AWK
- Bait
- BASIC
- BaCon
- BASIC256
- BBC BASIC
- Commodore BASIC
- Creative Basic
- FreeBASIC
- Gambas
- IS-BASIC
- IWBASIC
- Lambdatalk
- Liberty BASIC
- NS-HUBASIC
- PureBasic
- Run BASIC
- TI-89 BASIC
- VBA
- VBScript
- Visual Basic .NET
- Yabasic
- Batch File
- Bc
- Bracmat
- C
- C sharp
- C++
- C3
- Chapel
- Clojure
- CLU
- CMake
- COBOL
- ColdFusion
- Common Lisp
- D
- Dao
- Delphi
- Dragon
- Dyalect
- E
- EasyLang
- EchoLisp
- Ecstasy
- Ed
- Efene
- Eiffel
- Ela
- Elena
- Elixir
- Emacs Lisp
- Cl-lib
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- Fantom
- Fennel
- Forth
- Fortran
- Friendly interactive shell
- Frink
- FutureBasic
- GAP
- Go
- Groovy
- Halon
- Haskell
- Haxe
- HicEst
- Hy
- Icon
- Unicon
- Io
- J
- Java
- JavaScript
- Jq
- Jsish
- Julia
- K
- Klingphix
- Kotlin
- LabVIEW
- Lang
- Lang5
- Langur
- Lasso
- LDPL
- LFE
- LIL
- Lingo
- Lisaac
- LiveCode
- Logo
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- MAXScript
- Metafont
- Min
- MiniScript
- MOO
- Nanoquery
- Nemerle
- NetRexx
- NewLISP
- Nim
- Nu
- Objeck
- Objective-C
- OCaml
- Oforth
- Ol
- OoRexx
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- PHL
- PHP
- PicoLisp
- Pike
- PL/I
- Plain English
- Pop11
- PostScript
- PowerShell
- Prolog
- Python
- Quackery
- R
- Racket
- Raku
- REBOL
- Red
- ReScript
- Retro
- REXX
- Ring
- RPL
- Ruby
- Rust
- Salmon
- SAS
- Sather
- Scala
- Scheme
- Scilab
- Seed7
- Self
- SETL
- Sidef
- Slate
- Smalltalk
- Snabel
- Sparkling
- Standard ML
- Stata
- Suneido
- Swift
- SystemVerilog
- Tailspin
- Tcl
- Trith
- TUSCRIPT
- UNIX Shell
- C Shell
- V
- Vala
- Vim Script
- V (Vlang)
- Wart
- WDTE
- Wren
- XLISP
- XPL0
- XSLT
- Zig
- Zkl
- GUISS/Omit
- PL/0/Omit
- Tiny BASIC/Omit
- Pages with too many expensive parser function calls