June 13, 2018

Groovy Goodness: Getting All Init And Tail Values Recursively

For a long time we could get the tail or init values for a collection. Groovy 2.5.0 adds the methods inits and tails for Iterable objects. These methods return a List with List values where the first element is the original collection and the next is the result of init or tail on the previous element. This is repeated until the result of init or tail is an empty List.

In the next example script we have a original collection of letters. We first run the init and tail methods (without the s). Next we look at the result of invoking inits and tails:

def letters = ('a'..'d').toList()

assert letters == ['a', 'b', 'c', 'd']

assert letters.init() == ['a', 'b', 'c']
assert letters.tail() == ['b', 'c', 'd']

// Inits returns collection of all init()
// results for an Iterable. The first element
// has the original values, the next element
// the result of init()
// of the previous element and so on until
// an empty List is the result.
assert letters.inits() == [
    ['a', 'b', 'c', 'd'], 
    ['a', 'b', 'c'], 
    ['a', 'b'], 
    ['a'], 
    []]

// Tails returns collection of all tail()
// results for an Iterable. The first element
// has the original values, the next element
// the result of tail()
// of the previous element and so on until
// an empty List is the result.
assert letters.tails() == [
    ['a', 'b', 'c', 'd'], 
    ['b', 'c', 'd'], 
    ['c', 'd'], 
    ['d'], 
    []]

Written with Groovy 2.5.0.