Loops/Foreach: Difference between revisions
m (→{{header|C++}}: oops) |
(Added VBScript Example) |
||
Line 149: | Line 149: | ||
=={{header|V}}== |
=={{header|V}}== |
||
[1 2 3] [puts] step |
[1 2 3] [puts] step |
||
=={{header|VBScript}}== |
|||
dim items(2) |
|||
items(0)="Apple" |
|||
items(1)="Orange" |
|||
items(2)="Banana" |
|||
For Each x in items |
|||
WScript.Echo x |
|||
Next |
|||
=={{header|XSLT}}== |
=={{header|XSLT}}== |
Revision as of 20:02, 12 December 2008
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.
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.
<cpp>
for (container_type::iterator i = container.begin(); i != container.end(); ++i) { std::cout << *i << "\n"; }
</cpp> However the idiomatic way to output a container would be <cpp>
std::copy(container.begin(), container.end(), std::output_iterator<container_type::value_type>(std::cout, "\n"));
</cpp>
There's also an algorithm named for_each
. However, you need a function or function object to use it, e.g.
<cpp>
void print_element(container_type::value_type const& v)
{
std::cout << v << "\n";
}
...
std::for_each(container.begin(), container.end(), print_element);
</cpp>
The next version of the standard will allow the following simplified syntax: <cpp>
- include <iterator_concepts>
for (auto element: container) {
std::cout << element << "\n";
}
</cpp>
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:
<cpp>
- include <iterator_concepts>
for (auto const& element: container) {
std::cout << element << "\n";
} </cpp> 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. <d>foreach(element ; collection)
writefln(element);</d>
Forth
create a 3 , 2 , 1 , : .array ( a len -- ) cells bounds do i @ . cell +loop ; \ 3 2 1
Haskell
forM_ collect print
Java
<java>Collection<Type> collect; ... for(Type i:collect){
System.out.println(i);
}</java> 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)
OCaml
List of integers: <ocaml>List.iter
(fun i -> Printf.printf "%d\n" i) collect_list</ocaml>
Array of integers: <ocaml>Array.iter
(fun i -> Printf.printf "%d\n" i) collect_array</ocaml>
Perl
<perl>foreach $i (@collect) {
print "$i\n";
}</perl> The keyword for can be used instead of foreach. If a variable ($i) is not given, then $_ is used.
PHP
<php>foreach ($collect as $i) {
echo "$i\n";
}</php>
Pop11
Iteration over list:
lvars el, lst = [1 2 3 4 foo bar]; for el in lst do printf(el,'%p\n'); endfor;
Python
<python>for i in collection:
print i</python>
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:
<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 </python>
Ruby
for i in collection do
puts i
end
This is syntactic sugar for:
collection.each do |i|
puts i
end
Scheme
List: <scheme>(for-each
(lambda (i) (display i) (newline)) the_list)</scheme>
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
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>