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

minv/maxv where closure computes value

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • 1.0-beta-8
    • 1.0-beta-10
    • None
    • None

    Description

      It would be great to have an alternate form of min()/max() where closure returns a value to be compared, rather than a comparison. I'm often trying to choose the "most desirable" element of a list, and I have some expression that computes the desirability. Right now I have to do:

      mylist.max

      {x,y | my_desirability_expression(x) <=> my_desirability_expression(y) }

      That's wordy because I need to write the desirability expression twice, and I also need to have explicit arguments for the closure. It would be great if there were a "maxv" where I could write:

      mylist.maxv

      { my_desirability_expression(it) }

      maxv for "maximum of value." Similarly with minv.

      This is trivial to implement; here's what I use (a global function):

      def minv (l, Closure f) {
      return l.min

      { x, y | f(x) <=> f(y) }

      }

      Attachments

        1. GroovyMethodsTest.patch
          0.9 kB
          Martin C. Martin
        2. DefaultGroovyMethods_NEW.patch
          4 kB
          Martin C. Martin
        3. DefaultGroovyMethods.diff
          2 kB
          Martin C. Martin

        Activity

          People

            guillaume Guillaume Sauthier
            mcspanky Martin C. Martin
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: