« Return to Thread: Groovy syntax /API enhancement

Re: Groovy syntax /API enhancement

by Jochen Theodorou :: Rate this Message:

Reply to Author | View in Thread

Tom Nichols schrieb:

> On Sun, Apr 20, 2008 at 7:20 PM, Jochen Theodorou <blackdrag@...> wrote:
>
>>>   4. support everyWithIndex, anyWithIndex, collectWithIndex,
>>>
>>>      sumWithIndex etc. it's even better if the original every, any has
>>>      an implicit variable/syntax for retrieving the index
>>>      e.g. [10,20].collectWithIndex{ it,i -> it*(i+1) } = [ 10, 40 ]
>>>
>>  I am against all these withIndex methods... they are polluting the API so
>> much. I would like to have a more general solution, but I can't think of any
>> yet
>
> Can't you just modify the each/any/collect methods to test how many
> parameters the closure takes?

well, if you look at Map, then yo have a problem for "each", because one
argument means an iteration using the entry, 2 arguments means key and
value. There is no place for a each-version with two arguments meaning
the entry and index.  I am thinking currently about an index generating
closure, that calls your work closure with an additional parameter:

def index = 0
def indexGen = { closure, Object[] par ->
   closure.call(*par, index)
   index++
}

['a','b','c'].each indexGen.curry {item,index ->
                   println "$index: $item"}

with the ouput:
"""
0: a
1: b
2: c
"""

of course this is ugly on first sight... but indexGen is a generic piece
of code that could work with any closure... or be used as a method on
the closure:

['a','b','c'].each {item,index -> println "$index: $item"}.indexed

where indexed is a property on the closure that will return a new
closure containing the index. then it would work on *any* closure as
part of the closure, having less methods, but not loosing the
functionality. As that it can then be uased for each, any, find,
findAll, inject, collect ....

the only thing that keeps me from removing all withIndex methods from
DGM (and some others as well) and adding this to Closure is that I am
not fully satisfied with the syntax. Also in a GPath expression it might
be a bit confusing... so I am still searching for the "perfect" solution.

bye blackdrag

--
Jochen "blackdrag" Theodorou
The Groovy Project Tech Lead (http://groovy.codehaus.org)
http://blackdragsview.blogspot.com/
http://www.g2one.com/

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


 « Return to Thread: Groovy syntax /API enhancement