|
|
Re: standard for loop: msg#00199
lang.groovy.user
|
Subject: |
Re: standard for loop |
Awesome! Thanks to all for the help.
Should I add this info to the Wiki somewhere? Just occurred to me . . .
Scott S.
On Nov 30, 2004, at 1:20 AM, Marc Hedlund wrote:
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.j
av
a:1026)
at
org.codehaus.groovy.syntax.parser.ASTBuilder.statement(ASTBuilder.java
:
773)
at
org.codehaus.groovy.syntax.parser.ASTBuilder.topLevelStatement(ASTBuil
de
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
| |