Yes, it would be StringGroovyMethods. For better or worse, the current 
iterable-like
methods in SGM (dropWhile, collectReplacements, takeWhile) pass a char  into 
the Closure.
Here is the little experiment I did for count:

    /**
     * Counts the number of occurrences which satisfy the given closure from 
the chars within this CharSequence.
     * <p/>
     * Example usage:
     * <pre class="groovyTestCase">
     * assert "hello".count{ "aeiou".contains(it as String) } == 2
     * assert "hello".count{ String s -> "aeiou".contains(s) } == 2
     * </pre>
     *
     * @param self      the CharSequence within which we count the number of 
occurrences
     * @param condition a closure condition which is passed each character (or 
String of size 1 if the closure takes a String argument)
     * @return the number of occurrences
     * @since 2.5.0
     */
    public static <T> Number count(CharSequence self, 
@ClosureParams(value=SimpleType.class, options="char") Closure condition) {
        int index = 0;
        int result = 0;
        boolean stringArg = condition.getMaximumNumberOfParameters() == 1 && 
condition.getParameterTypes()[0].equals(String.class);
        BooleanClosureWrapper bcw = new BooleanClosureWrapper(condition);
        while (index < self.length()) {
            char value = self.charAt(index);
            if (bcw.call(stringArg ? Character.toString(value) : value)) {
                result++;
            }
            index++;
        }
        return result;
    }

This passes char in as the default but also will pass a String of size 1 if the 
provided
closure has one String arg - see the examples in the GroovyDoc.  Actually, in 
hindsight,
I would have made String of size 1 the default and char the thing to optionally 
look for.
But for consistency, not sure whether it is good to change that decision now.  
Then again,
if we want to make such a change we should do it before 2.5.0 and before we add 
a bunch
more methods.

Cheers, Paul.

On 23/05/2015 7:22 PM, Peter Ledbrook wrote:
    Currently you'd need to do something like:

    "hello".iterator().count{ "aeiou".contains(it) }

    I think it makes sense to add a direct DGM method in this instance.
    And yes, I suspect that CharSequence versions of most of the Iterable
    DGM methods would be appropriate.


Should these go in DGM or StringGroovyMethods? I'm thinking the simplest 
solution would be implementations of the form:

     static int count(CharSequence seq, Closure cl) {
         return count(seq.iterator(), cl);
     }

Does that make sense?

Peter


---
This email has been checked for viruses by Avast antivirus software.
http://www.avast.com

Reply via email to