Loops/Foreach: Difference between revisions
No edit summary |
(added objective c) |
||
Line 100: | Line 100: | ||
collection foreach(println) |
collection foreach(println) |
||
=={{header|Objective-C}}== |
|||
{{works with|Objective-C|2.0+}} |
|||
<lang objc>NSArray *collect; |
|||
... |
|||
for(Type i in collect){ |
|||
NSLog(@"%@", i); |
|||
}</lang> |
|||
''collect'' can be any object that adopts the NSFastEnumeration protocol. |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
List of integers: |
List of integers: |
Revision as of 09:01, 12 February 2009
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.
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.
Note: ALGOL 68S actually has a reserved word FOREACH that is used to break arrays in to portions, and process in parallel.
C++
C++ does not (yet) 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. <lang cpp>
for (container_type::iterator i = container.begin(); i != container.end(); ++i) { std::cout << *i << "\n"; }
</lang> However the idiomatic way to output a container would be <lang cpp>
std::copy(container.begin(), container.end(), std::output_iterator<container_type::value_type>(std::cout, "\n"));
</lang> There's also an algorithm named for_each. However, you need a function or function object to use it, e.g. <lang cpp> void print_element(container_type::value_type const& v) {
std::cout << v << "\n";
}
...
std::for_each(container.begin(), container.end(), print_element);
</lang>
The next version of the standard will allow the following simplified syntax: <lang cpp>
- include <iterator_concepts>
for (auto element: container) {
std::cout << element << "\n";
} </lang> 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: <lang cpp>
- include <iterator_concepts>
for (auto const& element: container) {
std::cout << element << "\n";
} </lang> Of course the container elements can also be changed by using a non-const reference (provided the container isn't itself constant).
Common Lisp
(loop for i in list do (print i))
D
This works if collection is an array/associative array type or a type that implements an appropriate opApply function. <lang d>foreach(element ; collection)
writefln(element);</lang>
Forth
create a 3 , 2 , 1 , : .array ( a len -- ) cells bounds do i @ . cell +loop ; \ 3 2 1
Haskell
forM_ collect print
Java
<lang java>Collection<Type> collect; ... for(Type i:collect){
System.out.println(i);
}</lang> This works for any array type as well as any type that implements the Iterable interface (including all Collections).
JavaScript
This works for any object, as well as arrays.
for (var a in o) print(o[a]);
Logo
foreach [red green blue] [print ?]
MAXScript
for i in collect do ( print i )
Io
collection foreach(println)
Objective-C
<lang objc>NSArray *collect; ... for(Type i in collect){
NSLog(@"%@", i);
}</lang> collect can be any object that adopts the NSFastEnumeration protocol.
OCaml
List of integers: <lang ocaml>List.iter
(fun i -> Printf.printf "%d\n" i) collect_list</lang>
Array of integers: <lang ocaml>Array.iter
(fun i -> Printf.printf "%d\n" i) collect_array</lang>
Perl
<lang perl>foreach $i (@collect) {
print "$i\n";
}</lang> The keyword for can be used instead of foreach. If a variable ($i) is not given, then $_ is used.
PHP
<lang php>foreach ($collect as $i) {
echo "$i\n";
}</lang>
Pop11
Iteration over list:
lvars el, lst = [1 2 3 4 foo bar]; for el in lst do printf(el,'%p\n'); endfor;
Python
<lang python>for i in collection:
print i</lang>
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:
<lang python> 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: chracters += 1
print lines, words, characters </lang>
Ruby
<lang ruby>for i in collection do
puts i
end</lang>
This is syntactic sugar for:
<lang ruby>collection.each do |i|
puts i
end</lang>
Scheme
List: <lang scheme>(for-each
(lambda (i) (display i) (newline)) the_list)</lang>
V
[1 2 3] [puts] step
VBScript
dim items(2) items(0)="Apple" items(1)="Orange" items(2)="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
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>