Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 79 ]

[1,3,5] + [["apple","orange","pear"]] == multidimensional
and: "also with the left shift operator"
[1,3,5] << ["apple","orange","pear"] == multidimensional
and: "we can Subtract elements with the minus operator"
multidimensional - [["apple","orange","pear"]] == [1,3,5]
and: "we can flatten that multi dimensional list"
multidimensional.flatten() == [1,3,5,"apple","orange","pear"]

There are also some convenience functions that make list management easier. In the
preceding code, we use the flatten method to flatten a multidimensional List. Next,
we can see the use of the reverse, collect, and grep find and sort methods and their
effect on a List:


given: "some Lists"
def odds = [1,3,5]
def evens = [2,4,6]
def animals = ["cat", "dog", "fox", "cow"]
expect: "we can reverse the order of a list"
odds.reverse() == [5,3,1]
and: "can apply a closure to a list to transform it using collect"
odds.collect { it + 1 } == evens
and: "we can find in the list using regex"
animals.grep( ~/.o./ ) == ["dog", "fox", "cow"]
and: "we can sort a list"
[5,1,3].sort() == odds
and: "we can find elements matching an expression"
animals.find { it == "dog" } == "dog"

We can iterate over a list in both directions by applying a closure to each item:


given:
def list = [1,3,5]
def number = ''
when: "we iterate forwards"
list.each { number += it }
then: "the numbers are added to the string in order"
number == '135'
when: "we iterate backwards"
number = ''
list.reverseEach { number += it }
then: "the numbers are added in reverse order"
number == '531'
Free download pdf