Skip to content

Instantly share code, notes, and snippets.

@onetom
Created April 20, 2011 17:43
Show Gist options
  • Save onetom/932103 to your computer and use it in GitHub Desktop.
Save onetom/932103 to your computer and use it in GitHub Desktop.
Error has been reported already and fixed in R2/Forward, but it hasn't made it into R2 yet
map-each: func [
"Evaluates a block for each value(s) in a series and returns them as a block."
[throw catch]
'word [word! block!] "Word or block of words to set each time (local)"
data [block!] "The series to traverse"
body [block!] "Block to evaluate each time"
/into "Collect into a given series, rather than a new block"
output [any-block! any-string!] "The series to output to" ; Not image!
/local init len x
][
; Shortcut return for empty data
either empty? data [any [output make block! 0]] [
; BIND/copy word and body
word: either block? word [
if empty? word [throw make error! [script invalid-arg []]]
copy/deep word ; /deep because word is rebound before errors checked
] [reduce [word]]
word: use word reduce [word]
body: bind/copy body first word
; Build init code
init: none
parse word [any [word! | x: set-word! (
unless init [init: make block! 4]
; Add [x: at data index] to init, and remove from word
insert insert insert tail init first x [at data] index? x
remove x
) :x | x: skip (
throw make error! reduce ['script 'expect-set [word! set-word!] type? first x]
)]]
len: length? word ; Can be zero now (for advanced code tricks)
; Create the output series if not specified
unless into [output: make block! divide length? data max 1 len]
; Process the data (which is not empty at this point)
until [ ; Note: output: insert/only output needed for list! output
set word data do init
unless unset? set/any 'x do body [output: insert/only output :x]
tail? data: skip data len
]
; Return the output and clean up memory references
also either into [output] [head output] (
set [word data body output init x] none
)
]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment