Loops/Foreach: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Added to iteration category)
(added ocaml)
Line 16: Line 16:
System.out.println(i);
System.out.println(i);
}</java>
}</java>
This works for any array type as well as any type that implements the Iterable interface (including all Collections).


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 23: Line 24:
=={{header|Logo}}==
=={{header|Logo}}==
foreach [red green blue] [print ?]
foreach [red green blue] [print ?]

=={{header|OCaml}}==
List:
<ocaml>List.iter
(fun i -> Printf.printf "%d\n" i)
collect_list</ocaml>

Array:
<ocaml>Array.iter
(fun i -> Printf.printf "%d\n" i)
collect_array</ocaml>


=={{header|Perl}}==
=={{header|Perl}}==

Revision as of 20:03, 15 April 2008

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.

Common Lisp

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

Forth

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

Java

Works with: Java version 1.5+

<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]);

foreach [red green blue] [print ?]

OCaml

List: <ocaml>List.iter

 (fun i -> Printf.printf "%d\n" i)
 collect_list</ocaml>

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

Python

<python>for i in collect:

  print i</python>