logo       

Re: standard for loop: msg#00197

lang.groovy.user

Subject: Re: standard for loop


Scott,

In addition to the answers you've already gotten, I would also recommend
using closures where you would have used a for loop. each() and
eachWithIndex() replace most for loops in my scripts.

Some examples follow...

/**********************/

stringList = [ "java", "perl", "python", "ruby", "c#", "cobol",
"groovy", "jython", "smalltalk", "prolog", "m", "yacc" ];

stringMap = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday",
"We" : "Wednesday", "Th" : "Thursday", "Fr" : "Friday",
"Sa" : "Saturday" ];

stringList.each() { print " ${it}" }; println "";
// java perl python ruby c# cobol groovy jython smalltalk prolog m yacc

stringMap.each() { key, value | println "${key} == ${value}" };
// Su == Sunday
// We == Wednesday
// Mo == Monday
// Sa == Saturday
// Th == Thursday
// Tu == Tuesday
// Fr == Friday

stringList.eachWithIndex() { obj, i | println " ${i}: ${obj}" };
// 0: java
// 1: perl
// 2: python
// 3: ruby
// 4: c#
// 5: cobol
// 6: groovy
// 7: jython
// 8: smalltalk
// 9: prolog
// 10: m
// 11: yacc

stringMap.eachWithIndex() { obj, i | println " ${i}: ${obj}" };
// 0: Su=Sunday
// 1: We=Wednesday
// 2: Mo=Monday
// 3: Sa=Saturday
// 4: Th=Thursday
// 5: Tu=Tuesday
// 6: Fr=Friday



Marc Hedlund
e: marc at precipice dot org

On Tue, 30 Nov 2004, Scott Stirling wrote:

> Hi,
>
> Is there a Groovy idiom (with a counter) to use instead of a standard
> 'for' loop? I need to use the counter from the loop iterations.
>
> I get this exception when I code a standard 'for' loop (i.e., for (int
> i =0; i < foo.size(); i++):
>
> Exception in thread "main" NOT YET IMPLEMENTED: standard for loop
> at
> org.codehaus.groovy.syntax.parser.ASTBuilder.forStatement(ASTBuilder.jav
> a:1026)
> at
> org.codehaus.groovy.syntax.parser.ASTBuilder.statement(ASTBuilder.java:
> 773)
> at
> org.codehaus.groovy.syntax.parser.ASTBuilder.topLevelStatement(ASTBuilde
> r.java:327)
> at
> org.codehaus.groovy.syntax.parser.ASTBuilder.build(ASTBuilder.java:198)
> at
> org.codehaus.groovy.control.SourceUnit.convert(SourceUnit.java:339)
>
> Thank you,
> Scott Stirling
> Framingham, MA
>



<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise