Idiom #6 Iterate over list values
Do something with each item x of the list (or array) items, regardless indexes.
- Scala
- Scala
- Scala
- Ada
- C
- C
- Caml
- Clojure
- Cobol
- C++
- C#
- D
- D
- Dart
- Elixir
- Elixir
- Erlang
- Erlang
- Fortran
- Go
- Groovy
- Groovy
- Groovy
- Haskell
- JS
- JS
- JS
- JS
- JS
- Java
- Java
- Java
- Java
- Java
- Java
- Kotlin
- Kotlin
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- PHP
- Pascal
- Perl
- Perl
- Python
- Python
- Python
- Ruby
- Ruby
- Rust
- Rust
- Scheme
- Scheme
- Scheme
- Smalltalk
- VB
- Ada
- C
- C
- Caml
- Clojure
- Cobol
- C++
- C#
- D
- D
- Dart
- Elixir
- Elixir
- Erlang
- Erlang
- Fortran
- Go
- Groovy
- Groovy
- Groovy
- Haskell
- JS
- JS
- JS
- JS
- JS
- Java
- Java
- Java
- Java
- Java
- Java
- Kotlin
- Kotlin
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- PHP
- Pascal
- Perl
- Perl
- Python
- Python
- Python
- Ruby
- Ruby
- Rust
- Rust
- Scheme
- Scheme
- Scheme
- Smalltalk
- VB
(map do-something items)
do-something should be a function that receives a single argument. map returns a lazy seq, which means the function do-something won't be applied until the results are needed.
for _, x := range items {
doSomething(x)
}
You have to explicitly ignore the index loop variable, with the blank identifier _
T t;
Iterator<T> i = items.listIterator();
while (i.hasNext()) {
t = i.next();
}
The `ListIterator` allows for backward iteration, and mutation.
T t;
Iterator<T> i = items.iterator();
while (i.hasNext()) {
t = i.next();
}
for (Item x: items) {
doSomething(x);
}
This syntax is allowed since Java 5.
It works with arrays or collections as well.
Item is the type of the elements.
It works with arrays or collections as well.
Item is the type of the elements.
array_map(func, $items);
Function does need to be a real function and not a language construct, so you can't directly map _- (the unary negation operator) or other function like constructs like echo or print
Do note, this fails for iteratable non-arrays, the foreach based approach is better in that situation.
Do note, this fails for iteratable non-arrays, the foreach based approach is better in that situation.
(define (doSomething x)
(if (not (null? x))
(begin
(display "Item=")
(display (car x))
(newline)
(doSomething (cdr x)))))
Iteration is achieved by recursion.
programming-idioms.org