Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-2838

Add everyWithIndex, anyWithIndex, collectWithIndex, sumWithIndex ... or add indexGen

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Major
    • Resolution: Won't Fix
    • 1.5.6, 1.6-beta-1
    • None
    • groovy-jdk
    • None

    Description

      The objective is that in any collection methods, the current index shall be available.

      Refer to the discussion at:
      http://www.nabble.com/Groovy-syntax--API-enhancement-td16796998.html#a16810531

      The discussion was long and the relevant content are extracted as follow for easy of reading:

      • 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 ]

      • The problem here is that you are assuming that those methods (every,
        any, collect, etc) are iterating over the collection with some
        predetermined order, in sequence. Nothing in the semantics says it
        should be so. They could be even be doing it in parallel.
      • 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
      • for 4..5, I did assume the collection is in sequence and is iteratable. It seems to me Groovy collections are usually in sequence by default. e.g. [] is ArrayList and [:].getClass() is LinkedHashMap, so in the majority of case, collection have order and have index. e.g. [] as Set is used, then the index will just be unavailable or always return -1.
      • Can't you just modify the each/any/collect methods to test how many
        parameters the closure takes? If the closure only takes one param
        assume it is the item. If it takes two params, assume (item, index).
        No?
      • That's what we're already doing for some of the methods like each().
        But it'd be nice to expand this approach to all methods for which it may apply.

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              mingfai Mingfai Ma
              Votes:
              9 Vote for this issue
              Watchers:
              5 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: