Loop/Foreach

From Rosetta Code

Jump to: navigation, search

Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.

Code examples should be formatted along the lines of one of the existing prototypes.
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.

Contents

[edit] 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.

 
  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::output_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);
 

The next version of the standard will allow the following simplified syntax:

 
#include <iterator_concepts>
 
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:

 
#include <iterator_concepts>
 
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).

[edit] Common Lisp

(loop for i in list do (print i))

[edit] D

This works if collection is an array/associative array type or a type that implements an appropriate opApply function.

foreach(element ; collection) 
  writefln(element);

[edit] Forth

create a 3 , 2 , 1 ,
: .array ( a len -- )
  cells bounds do  i @ .  cell +loop ;     \ 3 2 1

[edit] Haskell

forM_ collect print

[edit] Java

Works with: Java version 1.5+

Collection<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).

[edit] JavaScript

This works for any object, as well as arrays.

for (var a in o) print(o[a]);

[edit] Logo

foreach [red green blue] [print ?]

[edit] MAXScript

for i in collect do
(
    print i
)

[edit] Io

collection foreach(println)

[edit] 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

[edit] Perl

foreach $i (@collect) {
   print "$i\n";
}

The keyword for can be used instead of foreach. If a variable ($i) is not given, then $_ is used.

[edit] PHP

foreach ($collect as $i) {
   echo "$i\n";
}

[edit] Pop11

Iteration over list:

lvars el, lst = [1 2 3 4 foo bar];
for el in lst do
   printf(el,'%p\n');
endfor;

[edit] 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:
            chracters += 1
 
print lines, words, characters
 

[edit] Ruby

for i in collection do
  puts i
end

This is syntactic sugar for:

collection.each do |i|
  puts i
end

[edit] Scheme

List:

(for-each
  (lambda (i) (display i) (newline))
  the_list)

[edit] V

[1 2 3] [puts] step

[edit] 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 &gt;= 21]">
  <fo:block><xsl:value-of select="position()"/>. <xsl:value-of select="@name"/></fo:block>
</xsl:for-each>
Personal tools