Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

[REBOL] Re: Maplist?

From: joel:neely:fedex at: 9-Sep-2001 3:18

Hi, Ric, and all, Ric Gagliardi wrote:
> Let me throw my variation in. I found I often used similar > anonymous functions in map-like situations, so I made a > variation that uses a block representing the body of the > function instead: > > every: func [
...
> ] > for example, > > >> every [a b] [1 2 3 4 5 6] [a + b] > == [3 7 11] >
Very nice!
> Similarly, I have 'keep: > > keep: func [
...
> ] > > >> keep a [1 2 3 4 5 6] [even? a] > == [2 4 6] >
Being of a more primitive mind-set, (and being somewhat partial to FUNC, from my LISP days) I've often used something like:
>> map: function [[throw] f [any-function!] b [block!] /all] [
[ result item] [ [ result: make block! length? b [ foreach val b [ [ item: f val [ if any [found? item all] [ [ append/only result item]] [ result] == [0 2 4]
>> map func [x] [x * x] [0 1 2 3 4 5]
== [0 1 4 9 16 25] The point of the /ALL refinement becomes clearer when used with another useful function:
>> ident: func [[throw] f [any-function!] x [any-type!]] [
[ if f x [x] [ ]
>> ident :even? 3
== none
>> ident :odd? 3
== 3 so that IDENT gives back either the second argument or NONE, depending on whether the second argument passes the filter test given by the first argument. Combining these two allows all sorts of on-the-fly filtering, such as
>> map func [x] [ident :even? x] [0 1 2 3 4 5]
== [0 2 4] or even (calculational-obscurity warning! ;-)
>> repeat rem [0 1 2 3 4] [
[ print [rem ":" [ map [ func [x] [ident func [x] [(x * x) // 5 = rem] x] [ [0 1 2 3 4 5 6 7 8 9 10] [ ]] 0 : 0 5 10 1 : 1 4 6 9 2 : 3 : 4 : 2 3 7 8 (For those not into number theory, this shows which natural numbers have squares with various residues mod 5. Yawn...) Seriously, the example is somewhat contrived, but was put together to show the power of FUNC combined with higher-order functions (as in Ladislav's very rich collection referenced earlier in this thread). -jn- -- ------------------------------------------------------------ Programming languages: compact, powerful, simple ... Pick any two! joel'dot'neely'at'fedex'dot'com