[REBOL] MAP (was Re: Trace function)
From: joel::neely::fedex::com at: 22-Jun-2001 8:36
Hi, Christophe
CRS - Psy Sel/SPO, COUSSEMENT, Christophe, CPN
wrote:
> ... BTW I don't know *MAP* what does it means ?-
>
Here's a different variation that we kicked around on the list
a few months ago.
8<------------------------------------------------------------
map: function [
{apply function to all elements of block}
[throw]
f [any-function!]
b [block!]
/all
][
resb rese elem
][
resb: make block! length? b
foreach arge b [
if any [found? rese: f arge all] [
append/only resb rese
]
]
resb
]
8<------------------------------------------------------------
The /ALL refinement specifies whether to include NONE! values
in the result block. Sometimes you just want the results that
are actually meaningful. For example, given
addressbook: [
"Tom" [thomas--thomas--org]
"Dick" [richard--ricardo--com]
"Harry" [harold--barbers--net]
]
and
lookemup: func [who] [select addressbook who]
you can say
>> map :lookemup ["Tom" "Harry" "Nobody" "Dick" "Gonzo"]
== [[thomas--thomas--org][harold--barbers--net][richard--ricardo--com]]
to find any addresses you actually have, in contrast with
>> map/all :lookemup ["Tom" "Harry" "Nobody" "Dick" "Gonzo"]
== [[thomas--thomas--org][harold--barbers--net] none [richard--ricardo--com]
none]
Of course the latter allows you to ask, "Do I have addresses for
all of these people?"
>> all map/all :lookemup ["Tom" "Harry" "Nobody" "Dick" "Gonzo"]
== none
Finally, this version of MAP allows you to write quick filters
that create a block of selected values. Since
>> if-even: func [x] [if even? x [x]]
returns either its argument or NONE! depending on EVEN? (e.g.,
>> if-even 1 == none
>> if-even 2 == 2
we can say this:
>> map :if-even [0 1 2 3 4 5 6 7 8 9]
== [0 2 4 6 8]
or inline the filter, as in
>> map func [x] [if odd? x [x]] [0 1 2 3 4 5 6 7 8 9]
== [1 3 5 7 9]
HTH!
-jn-
--
It's turtles all the way down!
joel'dot'neely'at'fedex'dot'com