Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL
Help

Appendix D. Cheat sheets - Pg. 505

D. Cheat sheets Cheat sheets provide you with quick information and examples to get you up and running quickly. For more details about any topic, refer to the corresponding section in the book or on the Groovy web site's wiki. D.1. Lists See section 4.2. assert [1,2,3,4] == (1..4) assert [1,2,3] + [1] == [1,2,3,1] assert [1,2,3] << 1 == [1,2,3,1] assert [1,2,3,1] - [1] == [2,3] assert [1,2,3] * 2 == [1,2,3,1,2,3] assert [1,[2,3]].flatten() == [1,2,3] assert [1,2,3].reverse() == [3,2,1] assert [1,2,3].disjoint([4,5,6]) assert [1,2,3].intersect([4,3,1]) == [3,1] assert [1,2,3].collect{ it+3 } == [4,5,6] assert [1,2,3,1].unique().size() == 3 assert [1,2,3,1].count(1) == 2 assert [1,2,3,4].min() == 1 assert [1,2,3,4].max() == 4 assert [1,2,3,4].sum() == 10 assert [4,2,1,3].sort() == [1,2,3,4] assert [4,2,1,3].findAll{ it%2 == 0 } == [4,2] def animals = ['cat','kangaroo','koala','dog'] assert animals[2] == 'koala' def kanimals = animals[1..2] assert animals.findAll{ it =~ /k.*/ } == kanimals assert animals.find{ it =~ /k.*/ } == kanimals[0] assert animals.grep(~/k.*/) == kanimals D.2. Closures See chapter 5. def add = { x, y -> x + y } def mult = { x, y -> x * y } assert add(1,3) == 4 assert mult(1,3) == 3 def min = { x, y -> [x,y].min() } def max = { x, y -> [x,y].max() } def atLeastTen = max.curry(10) assert atLeastTen(5) == 10 assert atLeastTen(15) == 15 def pairWise(list, Closure invoke) { if (list.size() < 2) return [] def next = invoke(list[0],list[1]) return [next] + pairWise(list[1..-1], invoke) } assert pairWise(1..5, add) == [3, 5, 7, 9] assert pairWise(1..5, mult) == [2, 6, 12, 20] assert pairWise(1..5, min) == [1, 2, 3, 4] assert pairWise(1..5, max) == [2, 3, 4, 5] assert 'cbaxabc' == ['a','b','c'].inject('x'){ result, item -> item + result + item } 505