|REBOL 3 Docs||Guide||Concepts||Functions||Datatypes||Errors|
|TOC < Back Next >||Updated: 16-Aug-2010 Edit History|
Evaluates a block for each value(s) in a series.
word [word! block!] - Word or block of words to set each time (local)
data [series! any-object! map! none!] - The series to traverse
body [block!] - Block to evaluate each time
The foreach function repeats the evaluation of a block for each element of a series. It is used often in programs.
values: [11 22 33] foreach value values [print value] 11 22 33
Another example that prints each word in a block along with its value:
colors: [red green blue] foreach color colors [print [color get color]] red 255.0.0 green 0.255.0 blue 0.0.255
If the series is a string, each character will be fetched:
string: "REBOL" foreach char string [print char] R E B O L
This example will print each filename from a directory block:
files: read %. foreach file files [ if find file ".t" [print file] ] file.txt file2.txt newfile.txt output.txt
When a block contains groups of values that are related, foreach function can fetch all elements at the same time. For example, here is a block that contains a time, string, and price. By providing the foreach function with a block of words for the group, each of their values can be fetched and printed.
movies: [ 8:30 "Contact" $4.95 10:15 "Ghostbusters" $3.25 12:45 "Matrix" $4.25 ] foreach [time title price] movies [ print ["watch" title "at" time "for" price] ] watch Contact at 8:30 for $4.95 watch Ghostbusters at 10:15 for $3.25 watch Matrix at 12:45 for $4.25
In the above example, the foreach value block:
[time title price]
specifies that three values are to be fetched from movies for each evaluation of the block.
foreach [v1: v2] [1 2 3] [?? [v1 v2]] v1: [1 2 3] v2: 1 v1: [2 3] v2: 2 v1:  v2: 3
Notice that the v1 set-word does not affect the index position.
If you are using this option to remove values, please see the remove-each function which is many times faster for large series.
When using a single word argument, foreach will obtain the object field name or map key.
fruits: make object! [apple: 10 orange: 12 banana: 30] foreach field fruits [print field] apple orange banana
If a second word argument is provided, it will obtain the value of each entry:
foreach [field value] fruits [print [field value]] apple 10 orange 12 banana 30
The same behavior applies to the map! datatype, except that empty keys (those set to none) will be skipped.
When a set-word! is used in the variables block, it will obtain the object value itself.
|TOC < Back Next >||REBOL.com - WIP Wiki||Feedback Admin|