Contents:

1. Introduction

A very common idiom in REBOL is:

func [block /local result] [
 result: copy [ ]
 foreach val block [
  append result do-something-with val
 ]
 result
]

which the collect function turns into:

func [block] [
 collect [
  foreach val block [
   keep do-something-with val
  ]
 ]
]

2. Overview

Overview

collect: func [
 "Collect values passed to KEEP and return them"
 [throw]
 body [block!]
 /into result [series!] "Append values to this series"

 /local collect's locals
] [
 Collect values passed to keep
]
keep: func [
 "Append the value to the collection"
 [catch]
 value
 /only "Append a block value as a block"
] [
 Append value to the current collection
]

3. Collect values passed to keep

Collect values passed to keep

saved: collection
collection: any [result result: copy [ ]]
do body
collection: saved
result

3.1 collect's locals

collect's locals

saved

4. Append value to the current collection

Append value to the current collection

unless collection [
 throw make error! "KEEP outside of a COLLECT"
]
either only [
 append/only collection :value
] [
 append collection :value
]

5. Initialization

Overview +≡

collection: none