Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

As I have seen many questions asking tips for golfing in their interested language, I decided to ask for my favorite language: Groovy. People can give some tips and tricks that will be used in golfing with Groovy.

share|improve this question
    
Well this isn't very popular, is it :-( –  Alison Nov 29 '11 at 20:01
    
@Alison : I feel Bad, as there is no Golf tip for Groovy in this site :( –  Ant's Nov 30 '11 at 5:25
2  
Do you have any tips to start us off? –  Alison Nov 30 '11 at 11:50

3 Answers 3

I'm new to this whole golfing thing, this is what I got so far:

Use Closures not functions:

def a(b){print b}

is longer than

a={print it}

You can use a negative index in arrays and lists as an alias for size()-

c = "abc"
d = ["a", "b", "c"]

assert c[c.size()-1] == c[-1]
assert c[c.size()-2] == c[-2]
assert d[d.size()-1] == d[-1]
assert d.last() == d[-1]

The spread operator is a shortcut for collect:

assert d*.size() == d.collect{it.size()}

For sorting use the spaceship operator:

e = [54,5,12]
assert e.sort{a,b->a<=>b}==e.sort{a,b->a<b?-1:+1}
assert e.sort{a,b->a<=>b}==e.sort{a,b->if (a>b) {return(-1)} else {return(+1)}}

Edit Conversions:

assert "123" as int == "123".toInteger()
share|improve this answer
    
if on something listish the *.X spread operator can often be written as .X –  cfrick Jul 7 at 20:50

As Groovy is a somewhat verbose language, you could use Groovys MOP to shorten method calls.

The following snippet for example would pay off after the fourth usage:

''.metaClass.r<<{i->(int)Math.random()*i}
''.r(12)

Tip golfing edit:

0.metaClass.r<<{i->(int)Math.random()*i}
0.r(12)
share|improve this answer

grep is short and works on several problems

get the chars of a string as a list with spaces and without leading elements: 'ABC XYZ'.grep() returns [A, B, C, , X, Y, Z]

grep with regexp is shorther than converting to upper case, if required: it.grep(~/(?i)$c/) instead of it.toUpperCase().grep(c)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.