Loops/Foreach: Difference between revisions

From Rosetta Code
Content added Content deleted
(+AutoHotkey)
Line 111: Line 111:
<lang AutoHotkey>
<lang AutoHotkey>
string = mary,had,a,little,lamb
string = mary,had,a,little,lamb
loop, parse, string, `,
loop, parse, string, `,
{
{
msgbox %A_LoopField%
msgbox %A_LoopField%
}
}
}</lang>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==

Revision as of 20:13, 10 June 2009

Task
Loops/Foreach
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.

Ada

arrays

<lang Ada> 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; </lang>

doubly linked lists

Works with: Ada 2005

<lang Ada> 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; </lang>

vectors

Works with: Ada 2005

<lang Ada> 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; </lang>

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
[]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.

AmigaE

<lang 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</lang>

AutoHotkey

<lang AutoHotkey> string = mary,had,a,little,lamb loop, parse, string, `, { msgbox %A_LoopField% } </lang>

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

<lang awk>BEGIN {

 split("Mary had a little lamb", strs, " ")
 for(el in strs) {
   print strs[el]
 }

}</lang>

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 done:

<lang awk>for(i=1; i <= length(strs); i++) {

 print strs[i]

}</lang>

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>

  1. 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>

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

C#

<lang csharp>string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things) {

   Console.WriteLine(thing);

}</lang>

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>

E

<lang e>for e in theCollection {

   println(e)

}</lang>

In E, the for ... in ... loop is also used for iterating over numeric ranges; see Loop/For#E.

Forth

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

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]

Haskell

forM_ collect print

Java

Works with: Java version 1.5+

<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. <lang JavaScript>for (var a in o) print(o[a]);</lang> 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.

foreach [red green blue] [print ?]

MAXScript

<lang maxscript> for i in collect do (

   print i

) </lang>

Metafont

If we have a list of arbitrary items, we can simply use for:

<lang metafont>for x = "mary", "had", "a", "little", "lamb": message x; endfor end</lang>

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

<lang metafont>for x = for i = 1 upto 9: a[i], endfor, a[10]: show x; endfor end</lang>

works more like a foreach; we could make a macro to hide the strangeness of such a code.

Io

collection foreach(println)

Objective-C

Works with: Objective-C version 2.0+
Works with: GNUstep
Works with: Cocoa

<lang objc>NSArray *collect; //... for(Type i in collect){

  NSLog(@"%@", i);

}</lang> collect can be any object that adopts the NSFastEnumeration protocol.

Or (always using OpenStep compatible frameworks):

Works with: Objective-C version <2.0

<lang objc>NSArray *collect; //... NSEnumerator *enm = [collect objectEnumerator]; id i; while( (i = [enm nextObject]) ) {

 // do something with object i

}</lang>

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>

Octave

<lang 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 </lang>

We can also iterate over structures: <lang octave>x.a = [ 10, 11, 12 ]; x.b = { "Cell", "ul", "ar" }; for [ val, key ] = x

 disp(key);
 disp(val);

endfor</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";

}

foreach ($collect as $key => $i) {

  echo "\$collect[$key] = $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>

Slate

<lang slate>c do: [| :obj | print: obj].</lang>

Smalltalk

<lang smalltalk>aCollection do: [ :element | element displayNl ].</lang>

(Provided that the objects in the collection understand the displayNl method).

Standard ML

List of integers: <lang sml>app

 (fn i => print (Int.toString i ^ "\n"))
 collect_list</lang>

Array of integers: <lang sml>Array.app

 (fn i => print (Int.toString i ^ "\n"))
 collect_array</lang>

Tcl

<lang tcl>foreach item $list {

   puts $item

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