[REBOL] APL'ish operations Re:
From: bhandley:zip:au at: 25-Jul-2000 21:42
There are two ways you could go, depending on what you want.
Change each element within the series, or return a new series with the
result of your operation applied to each element.
For the first approach...
values-block: [1 2 3]
while [not tail? values-block] [
values-block: change values-block values-block/1 * 7
]
values-block: head values-block ; Sets the series back to it's head.
print values-block
For the second approach....
>> source-block: [1 2 3]
== [1 2 3]
>> result-block: make block! 3
== []
>> foreach elt source-block [
[ append result-block elt * 7
[ ]
== [7 14 21]
>> print result-block
7 14 21
For something more advanced...
With due credit to the original authors Ladislav Mecir and Carl Sassenrath.
Below is a function that does it. This function is advanced in the sense
that it takes a function as an argument. Passing the function in is done in
a special way.
map: func [{Maps a function to all elements of a block}
f [any-function!] blk [block!]
/local result
][
result: make block! length? blk
foreach elem blk [
append/only result f :elem
]
result
]
Use it like this:
>> my-func: func[x][ x * 7] ; Here I declare my function. my-func is a
word that refers to the created function.
>> map :my-func [1 2 3] ; Here I call map, the colon gets the value of
my-func word - in this case the function I created.
== [7 14 21]