Content deleted Content added
m →R: typo |
No edit summary |
||
(28 intermediate revisions by 14 users not shown) | |||
Line 1:
{{Short description|Control flow statement for traversing items in a collection}}
{{for|"for all" in logic (∀)|Universal quantification}}
[[File:For-Loop-Mint-Programming-Language-Type-2.gif|thumb|{{mono|foreach}} loops are almost always used to iterate over items in a sequence of elements.]]
{{Loop constructs}}<!--
In [[computer programming]], '''foreach loop''' (or '''for
| url=http://www.digitalmars.com/d/statement.html#ForeachStatement
| title=D Programming Language <code>foreach</code> Statement Documentation
Line 15:
== Syntax ==
Syntax varies among languages. Most use the simple word <code>for</code>, although other use the more logical word <code>foreach</code>, roughly as follows:
}
== Language support ==
[[Programming language]]s which support foreach loops include [[ABC (programming language)|ABC]], [[ActionScript]], [[Ada (programming language)|Ada]], [[C++]] (since [[C++11]]), [[C Sharp (programming language)|C#]], [[ColdFusion Markup Language]] (CFML), [[Cobra (programming language)|Cobra]], [[D (programming language)|D]], [[Daplex]] (query language), [[Delphi (software)|Delphi]], [[ECMAScript]], [[Erlang (programming language)|Erlang]], [[Java (programming language)|Java]] (since 1.5), [[JavaScript]], [[Lua (programming language)|Lua]], [[Objective-C]] (since 2.0), [[ParaSail (programming language)|ParaSail]], [[Perl]], [[PHP]], [[Prolog]],<ref>{{Cite web |url=https://www.swi-prolog.org/pldoc/man?predicate=foreach/2 |title=SWI-Prolog
▲[[Programming language]]s which support foreach loops include [[ABC (programming language)|ABC]], [[ActionScript]], [[Ada (programming language)|Ada]], [[C++11]], [[C Sharp (programming language)|C#]], [[ColdFusion Markup Language]] (CFML), [[Cobra (programming language)|Cobra]], [[D (programming language)|D]], [[Daplex]] (query language), [[Delphi (software)|Delphi]], [[ECMAScript]], [[Erlang (programming language)|Erlang]], [[Java (programming language)|Java]] (since 1.5), [[JavaScript]], [[Lua (programming language)|Lua]], [[Objective-C]] (since 2.0), [[ParaSail (programming language)|ParaSail]], [[Perl]], [[PHP]], [[Prolog]],<ref>{{Cite web|url=https://www.swi-prolog.org/pldoc/man?predicate=foreach/2|title=SWI-Prolog -- foreach/2|website=www.swi-prolog.org|access-date=2020-02-10}}</ref> [[Python (programming language)|Python]], [[R (programming language)|R]], [[REALbasic]], [[Rebol (programming language)|Rebol]],<ref>{{Cite web|url=http://www.rebol.com}}</ref> [[Red (programming language)|Red]],<ref>{{Cite web|url=http://www.red-lang.org}}</ref> [[Ruby (programming language)|Ruby]], [[Scala (programming language)|Scala]], [[Smalltalk]], [[Swift (programming language)|Swift]], [[Tcl]], [[tcsh]], [[Unix shell]]s, [[Visual Basic .NET]], and [[Windows PowerShell]]. Notable languages without foreach are [[C (programming language)|C]], and [[C++]] pre-C++11.
=== ActionScript 3.0 ===
[[ActionScript]] supports the ECMAScript 4.0 Standard<ref>{{cite web|url=https://www.ecma-international.org/activities/Languages/Language%20overview.pdf |title=Proposed ECMAScript 4th Edition – Language Overview |access-date=2020-02-21}}</ref> for <code>for each .. in</code><ref>{{cite web|url=https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#for_each..in |title=for each..in |access-date=2020-02-21}}</ref> which pulls the value at each index.
Line 53 ⟶ 52:
=== Ada ===
{{Wikibooks|Ada Programming|Control}}
[[Ada (programming language)|Ada]] supports foreach loops as part of the normal [[for loop]]. Say X is an [[Array data structure|array]]:
Line 124 ⟶ 122:
Most general: string or array as collection (collection size known at run-time)
: ''
<syntaxhighlight lang="c" highlight="5-8" line>
#include <stdio.h>
Line 174 ⟶ 172:
=== C++ ===
[[C++11]] provides a foreach loop. The syntax is similar to that of [[Foreach loop#Java|Java]]:
Line 205 ⟶ 202:
The compiler uses [[argument-dependent lookup]] to resolve the <code>begin</code> and <code>end</code> functions.<ref>{{cite web|url=https://en.cppreference.com/w/cpp/language/range-for |title=Range-based for loop (since C++11) |publisher=en.cppreference.com |access-date=2018-12-03}}</ref>
The [[C++ Standard Library]] also supports <code>for_each</code>,<ref>{{cite web|url=http://en.cppreference.com/w/cpp/algorithm/for_each |title=std::for_each - cppreference |publisher=en.cppreference.com |access-date=2017-09-30}}</ref> that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the
<syntaxhighlight lang="Cpp">
Line 266 ⟶ 263:
=== C++/CLI ===
The [[C++/CLI]] language proposes a construct similar to C#.
Line 282 ⟶ 278:
==== Script syntax ====
<syntaxhighlight lang="cfs">
// arrays
Line 322 ⟶ 317:
==== Tag syntax ====
<syntaxhighlight lang="CFM">
<!--- arrays --->
Line 339 ⟶ 333:
=== Common Lisp ===
[[Common Lisp]] provides foreach ability either with the ''dolist'' macro:
<syntaxhighlight lang="LISP">
Line 358 ⟶ 351:
=== D ===
{{Main|D (programming language)}}
<syntaxhighlight lang="D">
foreach(item; set) {
Line 375 ⟶ 367:
=== Dart ===
{{Main|Dart (programming language)}}
<syntaxhighlight lang="Java">
for (final element in someCollection) {
Line 383 ⟶ 374:
=== Object Pascal, Delphi ===
{{Main|Object Pascal|Delphi (software)}}
Foreach support was added in [[Delphi (
▲Foreach support was added in [[Delphi (programming language)|Delphi]] 2005, and uses an enumerator variable that must be declared in the ''var'' section.
<syntaxhighlight lang="Delphi">
Line 395 ⟶ 385:
=== Eiffel ===
The iteration (foreach) form of the [[Eiffel (programming language)|Eiffel]] loop construct is introduced by the keyword <code lang=Eiffel>across</code>.
Line 421 ⟶ 410:
=== Go ===
[[Go (programming language)|Go]]'s foreach loop can be used to loop over an array, slice, string, map, or channel.
Using the two-value form
<syntaxhighlight lang="go">
for index, value := range someCollection {
Line 431 ⟶ 419:
</syntaxhighlight>
Using the one-value form
<syntaxhighlight lang="go">
for index := range someCollection {
Line 439 ⟶ 427:
=== Groovy ===
[[Groovy (programming language)|Groovy]] supports ''for'' loops over collections like arrays, lists and ranges:
Line 470 ⟶ 457:
Collections in Groovy can also be iterated over using the ''each'' keyword
and a closure.
<syntaxhighlight lang="Groovy">
Line 478 ⟶ 465:
=== Haskell ===
[[
▲[[Haskell (programming language)|Haskell]] allows looping over lists with [[Monad (functional programming)|monadic]] actions using <code>mapM_</code> and <code>forM_</code> (<code>mapM_</code> with its arguments flipped) from [http://hackage.haskell.org/package/base-4.6.0.1/docs/Control-Monad.html Control.Monad]:
{| class="wikitable"
Line 517 ⟶ 503:
=== Java ===
In [[Java (programming language)|Java]], a foreach-construct was introduced in [[Java Development Kit]] (JDK) 1.5.0.<ref name="jdk5release">
"Enhanced for Loop - This new language construct[...]"
Line 544 ⟶ 529:
|year=2004
|publisher=[[Sun Microsystems, Inc.]]
}}</ref><ref name=Bloch>{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}</ref>{{rp|264}}
<syntaxhighlight lang="Java">
Line 552 ⟶ 537:
</syntaxhighlight>
Java also provides the stream api since java 8:<ref name=Bloch>{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}</ref>{{rp|294-203}}
<syntaxhighlight lang="Java">
List<Integer> intList = List.of(1, 2, 3, 4);
Line 566 ⟶ 551:
</syntaxhighlight>
Alternatively, function-based style: <ref>{{Cite web|url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach|title=Array.prototype.forEach() - JavaScript | MDN|date=16 December 2023 }}</ref>
<syntaxhighlight lang="JavaScript">
Line 600 ⟶ 585:
</syntaxhighlight>
=== Lua ===
=== Lua<ref>{{Cite web|url=https://en.wikibooks.org/wiki/Lua_Programming/Tables#Foreach_loop|title=Lua Programming/Tables - Wikibooks, open books for an open world|website=en.wikibooks.org|language=en|access-date=2017-12-06}}</ref> ===▼
{{Main|Lua (programming language)}}
▲
Iterate only through numerical index values:<syntaxhighlight lang="lua">
for index, value in ipairs(array) do
Line 613 ⟶ 600:
=== Mathematica ===
In [[Mathematica]], <code>Do</code> will simply evaluate an expression for each element of a list, without returning any value.
Line 631 ⟶ 617:
=== MATLAB ===
{{Main|MATLAB}}
<syntaxhighlight lang="MATLAB">
for item = array
Line 639 ⟶ 624:
=== Mint ===
For each loops are supported in Mint, possessing the following syntax:
<syntaxhighlight lang="Ruby">
Line 669 ⟶ 653:
=== Objective-C ===
Foreach loops, called [[Objective-C#Fast enumeration|Fast enumeration]], are supported starting in [[Objective-C]] 2.0. They can be used to iterate over any object that implements the NSFastEnumeration protocol, including NSArray, NSDictionary (iterates over keys), NSSet, etc.
Line 675 ⟶ 658:
NSArray *a = [NSArray new]; // Any container class can be substituted
for(id obj in a) { //
//
//
printf("%s\n", [[obj description] UTF8String]); // Must use UTF8String with %s
Line 716 ⟶ 699:
=== OCaml ===
[[OCaml]] is a [[functional
▲[[OCaml]] is a [[functional language]]. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays.
For lists:
Line 744 ⟶ 726:
=== ParaSail ===
The [[ParaSail (programming language)|ParaSail]] parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container:
Line 766 ⟶ 747:
=== Pascal ===
In [[Pascal (programming language)|Pascal]], ISO standard 10206:1990 introduced iteration over [[Pascal (programming language)#Set types|set types]], thus:
Line 781 ⟶ 761:
=== Perl ===
In [[Perl]], ''foreach'' (which is equivalent to the shorter for) can be used to traverse elements of a list. The expression which denotes the collection to loop over is evaluated in list-context and each item of the resulting list is, in turn, aliased to the loop variable.
Line 826 ⟶ 805:
=== PHP ===
{{Main|PHP syntax and semantics}}
<syntaxhighlight lang="php">
foreach ($set as $value) {
Line 845 ⟶ 823:
<syntaxhighlight lang="php">
$arr = array(1, 2, 3);
foreach ($arr as &$value) { //
$value++;
}
Line 859 ⟶ 837:
=== Python ===
{{Main|Python (programming language)}}
<syntaxhighlight lang="python">
for item in iterable_collection:
Line 889 ⟶ 866:
=== R ===
{{Main|R (programming language)}}
<syntaxhighlight lang="R">
for (item in object) {
Line 919 ⟶ 895:
=== Raku ===
In [[Raku (programming language)|Raku]], a sister language to Perl, ''for'' must be used to traverse elements of a list (''foreach'' is not allowed). The expression which denotes the collection to loop over is evaluated in list-context, but not flattened by default, and each item of the resulting list is, in turn, aliased to the loop variable(s).
Line 993 ⟶ 968:
=== Ruby ===
{{Main|Ruby (programming language)}}
<syntaxhighlight lang="Ruby">
set.each do |item|
Line 1,011 ⟶ 985:
<syntaxhighlight lang="Ruby">
set.each do |
# do something to
# do something to value
end
Line 1,019 ⟶ 993:
=== Rust ===
{{Main|Rust (programming language)}}
The <code>for</code> loop has the structure <
▲The <code>for</code> loop has the structure <code><nowiki>for <pattern> in <expression> { /* optional statements */ }</nowiki></code>. It implicitly calls the [https://doc.rust-lang.org/std/iter/trait.IntoIterator.html <code>IntoIterator::into_iter</code>] method on the expression, and uses the resulting value, which must implement the [https://doc.rust-lang.org/std/iter/trait.Iterator.html <code>Iterator</code>] trait. If the expression is itself an iterator, it is used directly by the <code>for</code> loop through an [https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#impl-IntoIterator-25 implementation of <code>IntoIterator</code> for all <code>Iterator</code>s] that returns the iterator unchanged. The loop calls the <code>Iterator::next</code> method on the iterator before executing the loop body. If <code>Iterator::next</code> returns <code>[[option type|Some(_)]]</code>, the value inside is assigned to the [[pattern matching|pattern]] and the loop body is executed; if it returns <code>None</code>, the loop is terminated.
<syntaxhighlight lang="Rust">
Line 1,053 ⟶ 1,026:
=== Scala ===
{{Main|Scala (programming language)}}
<syntaxhighlight lang="Scala">
// return list of modified elements
Line 1,087 ⟶ 1,059:
=== Swift ===
[[Swift (programming language)|Swift]] uses the <code>for</code>…<code>in</code> construct to iterate over members of a collection.<ref>{{Cite web|url=https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_153|title=Control Flow — the Swift Programming Language (Swift 5.5)}}</ref>
Line 1,111 ⟶ 1,082:
=== SystemVerilog ===
[[SystemVerilog]] supports iteration over any vector or array type of any dimensionality using the <code>foreach</code> keyword.
Line 1,154 ⟶ 1,124:
=== Tcl ===
[[Tcl]] uses foreach to iterate over lists. It is possible to specify more than one iterator variable, in which case they are assigned sequential values from the list.
{| class="wikitable"
Line 1,187 ⟶ 1,156:
|}
=== Visual Basic (.NET) ===
{{Main|Visual Basic (.NET)}}
<syntaxhighlight lang="VBNet">
For Each item In enumerable
Line 1,246 ⟶ 1,215:
{{Reflist|2}}
[[Category:Control flow]]▼
[[Category:Iteration in programming]]
[[Category:Programming language comparisons]]▼
<!-- Hidden categories below -->
[[Category:Articles with example Ada code]]
[[Category:Articles with example C Sharp code]]
[[Category:Articles with example D code]]
[[Category:Articles with example Eiffel code]]
[[Category:Articles with example Haskell code]]
[[Category:Articles with example Java code]]
[[Category:Articles with example JavaScript code]]
[[Category:Articles with example Lisp (programming language) code]]
[[Category:Articles with example MATLAB/Octave code]]
[[Category:Articles with example Objective-C code]]
[[Category:Articles with example OCaml code]]
[[Category:Articles with example Pascal code]]
[[Category:Articles with example Perl code]]
[[Category:Articles with example PHP code]]
[[Category:Articles with example Python (programming language) code]]
[[Category:Articles with example R code]]
[[Category:Articles with example Racket code]]
[[Category:Articles with example Ruby code]]
[[Category:Articles with example Rust code]]
[[Category:Articles with example Scala code]]
[[Category:Articles with example Scheme (programming language) code]]
[[Category:Articles with example Smalltalk code]]
[[Category:Articles with example Swift code]]
[[Category:Articles with example Tcl code]]
▲[[Category:Control flow]]
▲[[Category:Programming language comparisons]]
▲[[Category:Articles with example Java code]]
▲[[Category:Articles with example Haskell code]]
[[ru:Цикл просмотра]]
|