Loop structures: Difference between revisions
Content added Content deleted
(list comprehension) |
No edit summary |
||
Line 259: | Line 259: | ||
error" Ran out of records looking for the right one!" |
error" Ran out of records looking for the right one!" |
||
THEN |
THEN |
||
==[[Groovy]]== |
|||
[[Category:Groovy]] |
|||
===While Loops=== |
|||
while (true) { |
|||
println 'groovy' |
|||
} |
|||
===For Loops=== |
|||
<pre> |
|||
// iterate over a range |
|||
x = 0 |
|||
for (i in 1..3) { x += i } |
|||
assert x == 6 |
|||
// iterate over a list |
|||
x = 0 |
|||
for (i in [1, 2, 3]) { x += i } |
|||
assert x == 6 |
|||
// iterate over an array |
|||
x = 0 |
|||
for (i in (1..3).toArray()) { x += i } |
|||
assert x == 6 |
|||
// iterate over a map's key/value pairs |
|||
x = 0 |
|||
for (i in map) { x += i.value } |
|||
assert x = 6 |
|||
// iterate over a map's values |
|||
x = 0 |
|||
for (i in map.values()) { x += i } |
|||
assert x == 6 |
|||
// iterate over the characters in a string |
|||
text = 'abc' |
|||
list = [] |
|||
for (c in text) { list.add(c) } |
|||
assert list == ['a', 'b', 'c'] |
|||
</pre> |
|||
===Closures=== |
|||
<pre> |
|||
def stringList = [ "java", "perl", "python", "ruby" ]; |
|||
def stringMap = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday", |
|||
"We" : "Wednesday", "Th" : "Thursday", "Fr" : "Friday", |
|||
"Sa" : "Saturday" ]; |
|||
stringList.each() { print " ${it}" }; println ""; |
|||
// java perl python ruby |
|||
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 |
|||
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 |
|||
</pre> |
|||
==[[IDL]]== |
==[[IDL]]== |