Search

Dark theme | Light theme
Showing posts with label GroovyGoodness:Closure. Show all posts
Showing posts with label GroovyGoodness:Closure. Show all posts

February 23, 2020

Groovy Goodness: Lambda Default Parameter Value

Groovy 3 adds support for Java's lambda syntax expressions. This way we can write code in Groovy using lambda expressions just like in Java. But Groovy adds an additional feature and that is default parameter values for lambda expressions.

In the following example we use a default parameter value for a lambda expression.

// Groovy 3 supports Java's lambda syntax expressions.
def inc = n -> n + 1

assert inc(1) == 2


// But also adds default parameter values.
def multiplyBy = (n, factor = 2) -> n * factor

assert multiplyBy(1) == 2
assert multiplyBy(1, 10) == 10

Written with Groovy 3.0.1.

June 12, 2018

Groovy Goodness: Easy Object Creation With Tap Method

Groovy 2.5.0 adds the tap method to all objects and changes the method signature of the with method. In a previous post we already learned about the with method. In Groovy 2.5.0 we can add an extra boolean argument to the with method. If the value is false (is default) the with method must return the same value as what the closure invocation returns. If the value is true the object instance on which the with method is invoked is returned. The new tap method is an alias for with(true), so it will always return the object instance.

In the first example we use the tap method to create a new Sample object and set property values and invoke methods of the Sample class:

/** 
 * Sample class with some properties
 * and a method.
 */
class Sample {
    
    String username, email
    
    List<String> labels = []
    
    void addLabel(value) { 
        labels << value 
    }
    
}

// Use tap method to create instance of 
// Sample and set properties and invoke methods. 
def sample = 
        new Sample().tap {
            assert delegate.class.name == 'Sample'
            
            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'
            
            // We use tap, an alias for with(true), 
            // so the delegate of the closure, 
            // the Sample object, is returned.
        }

assert sample.labels == ['Groovy', 'Gradle']
assert sample.username == 'mrhaki'
assert sample.email == 'email@host.com'

In the following example we use the with method to demonstrate the differences for several invocations using different argument values:

/** 
 * Sample class with some properties
 * and a method.
 */
class Sample {
    
    String username, email
    
    List<String> labels = []
    
    void addLabel(value) { 
        labels << value 
    }
    
}

// Use with method to create instance of 
// Sample and set properties and invoke methods. 
def sample1 = 
        new Sample().with {
            assert delegate.class.name == 'Sample'

            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'   
        }
       
// With method returns the result 
// from the closure. In the previous
// case the return result is null,
// because the last statement addLabel
// is used as return value. addLabel has
// return type void.
assert !sample1


// Use with method to create instance of 
// Sample and set properties and invoke methods. 
def sample2 = 
        new Sample().with {
            assert delegate.class.name == 'Sample'

            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'
            
            // Explicitly return delegate of
            // closure, which is the Sample object.
            return delegate
        }

assert sample2.labels == ['Groovy', 'Gradle']
assert sample2.username == 'mrhaki'
assert sample2.email == 'email@host.com'


// Use with method to create instance of 
// Sample and set properties and invoke methods. 
def sample3 = 
        new Sample().with(true) {
            assert delegate.class.name == 'Sample'

            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'
            
            // We use with(true), so the 
            // delegate of the closure, the Sample
            // object, is returned.
        }

assert sample3.labels == ['Groovy', 'Gradle']
assert sample3.username == 'mrhaki'
assert sample3.email == 'email@host.com'

A good use case for using the with method is to transform an object to another type using values from the object. In the next example we use values from a Sample objects to create a new String:

/** 
 * Sample class with some properties
 * and a method.
 */
class Sample {
    
    String username, email
    
    List<String> labels = []
    
    void addLabel(value) { 
        labels << value 
    }
    
}

def sample = 
        new Sample().tap {
            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'
        }

// The with method can be very useful to
// transform object to another type using
// values from the object.
def user = sample.with { "$username likes ${labels.join(', ')}." }

assert user == 'mrhaki likes Groovy, Gradle.'

Written with Groovy 2.5.0.

October 31, 2016

Groovy Goodness: Identity Closure

In functional programming we have the concept of an identity function. An identity function returns the same result as the input of the function. Groovy has a lot of functional paradigms including a identity function. Of course in Groovy's case it is an identity closure. It is defined as a constant in the Closure class: Closure.IDENTITY. If we use this closure we get the same result as the argument we provide.

In the following example we first create our own identity closure. Next we use the built-in Closure.IDENTITY closure:

// Identity closure should return the same value
// as the input.
def identity = { a -> a }
assert identity(42) == 42
assert identity('Groovy rocks!') == 'Groovy rocks!'


// Groovy adds constant Closure.IDENTITY to 
// represent an identity closure:
assert Closure.IDENTITY('Groovy rocks!') == 'Groovy rocks!'
assert Closure.IDENTITY(['Groovy', 'is', 'gr8']) == ['Groovy', 'is', 'gr8']
assert Closure.IDENTITY(a: 1, b: 2, c: 3) == [a: 1, b: 2, c: 3]

// With static import we can reference
// the constant identity closure as well.
import static groovy.lang.Closure.IDENTITY
assert IDENTITY(42) == 42


// Can be useful to create a 
// Closure for constant values.
def theAnswer = IDENTITY.curry(42)
assert theAnswer() == 42


// Useful default for Closure method argument.
// Without default for the transform argument, 
// we have to pass two arguments.  
// Now the method accepts a single argument as well.
def transformString(String value, Closure transform = Closure.IDENTITY) {
   transform(value)
}

// Use default transform value (Closure.IDENTITY).
assert transformString('hubert') == 'hubert'

// Use custom transform Closure argument.
assert transformString('mrhaki') { s -> s.toUpperCase() } == 'MRHAKI'

Written with Groovy 2.4.7.

April 15, 2015

Groovy Goodness: Use Closures as Java Lambda Expressions

Java 8 introduced lambda expressions we can use for example with the new Java Streams API. The Groovy syntax doesn't support the lambda expressions, but we can rely on closure coersion to use Groovy closures as Java lambda expressions in our code.

In the following sample we use the Java Streams API. Instead of lambda expressions for the filter and map methods we use Groovy closures. They are automatically transformed to lambda expressions, so it is very easy to use Java streams from Groovy code.

import groovy.transform.*

/**
 * Simple class to describe
 * a Building.
 */
@Canonical
class Building {
    String name
    int floors
    boolean officeSpace
}

// Create Building objects.
def officeSpace = new Building('Initech office', 3, true)
def theOffice = new Building('Wernham Hogg Paper Company', 4, true)
def coffeeShop = new Building('Hunter Green', 1, false)

// And add to a list.
def buildings = [officeSpace, theOffice, coffeeShop]

// Create a closure which we will use 
// later in our code.
def mapBuildingName = { building -> building.name }


// Invoke Java Streams API with lambda methods,
// but we use Groovy closures.
def officeBuildingNames = 
    buildings
        .stream() // Get Java streams.
        .filter { building -> 
            building.officeSpace && building.floors > 2 
        } // 'anonymous' closure.
        .map(mapBuildingName) // Predefined closure.
        .collect()
        
assert officeBuildingNames == ['Initech office', 'Wernham Hogg Paper Company']

Code written with Groovy 2.4.3.

October 14, 2014

Groovy Goodness: Closure as a Class

When we write Groovy code there is a big chance we also write some closures. If we are working with collections for example and use the each, collect or find methods we use closures as arguments for these methods. We can assign closures to variables and use the variable name to reference to closure. But we can also create a subclass of the Closure class to implement a closure. Then we use an instance of the new closure class wherever a closure can be used.

To write a closure as a class we must subclass Closure and implement a method with the name doCall. The method can accept arbitrary arguments and the return type can be defined by us. So we are not overriding a method doCall from the superclass Closure. But Groovy will look for a method with the name doCall to execute the closure logic and internally use methods from the Closure superclass.

In the following sample we write a very simple closure as a class to check if an object is a number. Then we use an instance of the class with the findAll method for a collection of objects:

class IsNumber extends Closure<Boolean> /* return type for closure as generic type */ {

    IsNumber() {
        super(null)
    }

    /**
     * Implementation of closure.
     */
    Boolean doCall(final Object value) {
        // Check if value is a number, if so
        // return true, otherwise false.
        value in Number
    }

}

def list = ['a', 100, 'Groovy', 1, 8, 42.0, true]

def numbers = list.findAll(new IsNumber())

assert numbers == [100, 1, 8, 42.0]

Code written with Groovy 2.3.7.

April 4, 2014

Groovy Goodness: Closure as Writable

In a previous post we learned about the Writable interface and how the GString implementation implements this interface. In Groovy we can also use a closure as an implementation of the Writable interface. The Closure class has the method asWritable() that will return a version of the closure with an implementation of the writeTo() method. The Writer object that is used as an argument for the writeTo() method will be passed as argument to the closure. The asWritable() method also adds a toString() implementation for the closure to return the result of a closure as a String.

In the following code we write a sample make() method. The make() method return a Writable closure. The closure is only executed when the writeTo() or toString() method is invoked.

Writable make(Map binding = [:], Closure template) {
    // Use asWritable() to make the closure
    // implement the Writable interface.
    def writableTemplate = template.asWritable()
    
    // Assing binding map as delegate so we can access
    // the keys of the maps as properties in the 
    // closure context.
    writableTemplate.delegate = binding
    
    // Return closure as Writable.
    writableTemplate
}

// Use toString() of Writable closure.
assert make { Writer out -> out <<  "Hello world!" }.toString() == 'Hello world!'

// Provide data for the binding.
// The closure is not executed when the 
// make method is finished.
final writable = make(user:'mrhaki', { out ->
    out.println "Welcome ${user},"
    out.print "Today on ${new Date(year: 114, month: 3, date: 4).format('dd-MM-yyyy')}, "
    out.println "we have a Groovy party!"
})

// We invoke toString() and now the closure
// is executed.
final result = writable.toString()

assert result == '''Welcome mrhaki,
Today on 04-04-2014, we have a Groovy party!
'''

// Append contents to a file.
// NOTE: The leftShift (<<) operator on File is implemented
// in Groovy to use the File.append() method.
// The append() method creates a new Writer and
// invokes the write() method which 
// is re-implemented in Groovy if the argument
// is a Writable object. Then the writeTo() method
// is invoked:
// Writer.write(Writable) becomes Writable.writeTo(Writer).
// So a lot of Groovy magic allows us to use the following one-liner
// and still the writeTo() method is used on Writable.
new File('welcome.txt') << writable

assert new File('welcome.txt').text == '''Welcome mrhaki,
Today on 04-04-2014, we have a Groovy party!
'''

Code written with Groovy 2.2.2

November 19, 2013

Groovy Goodness: Implicit Closure Coercion

Groovy is awesome and closures are cool. In Java 8 we will see lambdas which are similar like closures. A Java lambda will be automatically converted to an interface type if the interface contains only one single abstract method (SAM). In Groovy we can convert a closure into an interface type by using the as keyword. But since Groovy 2.2 we don't have to use the as keyword, but let Groovy, like Java lambdas, convert a closure implicitly to an interface type. This works for interfaces with a single method, but Groovy wouldn't be Groovy if it didn't work for abstract classes with one abstract method. So, yes, it also works for abstract classes with a single abstract method.

In the following code we define a new class User and make the class send out PropertyChangeEvent events when a property value changes by applying the @Bindable AST transformation to the class. The @Bindable annotation will make sure all code is generated in the class file to inform classes implementing the PropertyChangeListener interface of changes in property values. The nice thing about the PropertyChangeListener interface is that is contains a single method and applies to Single Abstract Method (SAM). In the sample we use a closure that is automatically converted to a PropertyChangeListener type.

import groovy.beans.*
import java.beans.*

@Bindable
class User {
    String name, email
}

def u = new User(name: 'mrhaki', email: 'mrhaki@mrhaki.com')

// Since Groovy 2.2 we don't have to use the as keyword like
// { ... } as PropertyChangeListener,
// but we can rely on implicit coercion.
u.addPropertyChangeListener { event ->
    println "Changed property $event.propertyName from $event.oldValue to $event.newValue"
}

u.name = 'Hubert A. Klein Ikkink'
// Output: Changed property name from mrhaki to Hubert A. Klein Ikkink

u.email = 'hubert@mrhaki.com'
// Output: Changed property email from mrhaki@mrhaki.com to hubert@mrhaki.com

In the next sample we define an abstract class ChangedProperty with a single abstract method (SAM) as listener implementation. When we define an instance we can use a closure and it will automatically be the implementation of the abstract method:

import groovy.beans.*
import java.beans.*

@Bindable
class User {
    String name, email
}

def u = new User(name: 'mrhaki', email: 'mrhaki@mrhaki.com')

// Assign closure as implementation of single abstract method onPropertyChange
// in abstract class ChangedProperty.
ChangedProperty changedProperty = { event -> 
    println "Changed property $event.propertyName from $event.oldValue to $event.newValue" 
}
u.addPropertyChangeListener changedProperty

u.name = 'Hubert A. Klein Ikkink'
// Output: Changed property name from mrhaki to Hubert A. Klein Ikkink

u.email = 'hubert@mrhaki.com'
// Output: Changed property email from mrhaki@mrhaki.com to hubert@mrhaki.com

assert changedProperty.events.size() == 2
assert changedProperty.events.first().oldValue == 'mrhaki'
assert changedProperty.events.first().newValue == 'Hubert A. Klein Ikkink'

abstract class ChangedProperty implements PropertyChangeListener {

    List<PropertyChangeEvent> events = []

    void propertyChange(PropertyChangeEvent event) {
        events << event
        onPropertyChange(event);
    }
    
    abstract void onPropertyChange(PropertyChangeEvent event)

}

Code written with Groovy 2.2.

October 2, 2012

Groovy Goodness: Return Closure From Another Closure or Method

Groovy closures are powerful. A closure can be passed to methods as argument or defined as a variable. We can even return closures from methods or other closures. We can use the returned closure to execute the logic from the closure with the explicit call() method or the implicit syntax with just the closure object followed by opening and closing parentheses (()).

// Method returns a closure. Method could
// also have been another closure to return
// the closure.
def repeater(times) {
    { value -> value * times }
}

// Use explicit call() method on the return closure
// object from the repeater() method.
assert repeater(2).call('mrhaki') == 'mrhakimrhaki'

// Use implicit call() method on the return closure
// object from the repeater() method. This
// might looks strange at first...
assert repeater(2)('mrhaki') == 'mrhakimrhaki'

We can even use a closure parameter and use it in the return closure code. We rewrite the previous example and this time use a closure instead of method to define repeater:

// Extra transformer argument with default 
// closure implementation.
def repeater = { times, transformer = { it } ->
    { value -> transformer(value) * times }
}

assert repeater(2).call('mrhaki') == 'mrhakimrhaki'
assert repeater(2)('mrhaki') == 'mrhakimrhaki'

assert repeater(2) { it.toUpperCase() } ('mrhaki') == 'MRHAKIMRHAKI'
assert repeater(2, { it.reverse() })('mrhaki') == 'ikahrmikahrm'

Notice we define a transformer parameter that has a default closure that simply returns the argument of the closure, so the old assertions still work. At lines 9 and 10 we pass a closure as argument to the repeater closure using two different syntaxes.

(Code written with Groovy 2.0.4)

May 2, 2011

Groovy Goodness: Cache Closure Results with Memoization

Closures are very powerful in Groovy. Groovy 1.8 introduces closure memoization. This means we can cache the result of a closure, so the next time we invoke the closure the result is returned immediately. This is very useful for time consuming computations in a closure.

To use this feature we invoke the memoize() method on a closure. Now the results from calls to the closure are cached. We can use three other methods to define for example the maximum number of calls to cache, or the least number of calls with memoizeAtMost(), memoizeAtLeast() and memoizeBetween().

// Closure simple increments parameter.
// Also script variable incrementChange is 
// changed so we can check if the result is
// from a cached call or not.
def incrementChange = false
def increment = { 
    incrementChange = true
    it + 1 
}
// Just invoke the closure 5 times with different parameters.
(0..5).each {
    incrementChange  = false
    assert increment(it) == it + 1
    assert incrementChange
}
incrementChange = false
assert increment(1) == 2  // Call is not cached.
assert incrementChange  

// Use memoize() so all calls are cached.
incrementChange = false
def incrementMemoize = increment.memoize()
// Just invoke the closure 5 times with different parameters.
(0..5).each {
    incrementChange = false
    assert incrementMemoize(it) == it + 1
    assert incrementChange
}
incrementChange = false
assert incrementMemoize(2) == 3  // Cached call.
assert !incrementChange  

// Use memoizeAtMost().
incrementChange = false
def memoizeAtMostOnce = increment.memoizeAtMost(1)
// Just invoke the closure 5 times with different parameters.
(0..5).each {
    incrementChange = false
    assert memoizeAtMostOnce(it) == it + 1
    assert incrementChange
}
incrementChange = false
assert memoizeAtMostOnce(1) == 2  // 2nd call is not cached.
assert incrementChange  

April 28, 2011

Groovy Goodness: Recursion with Closure Trampoline Capability

When we write recursive code we might get a stack overflow exception, because calls are placed on the stack to be resolved. Since Groovy 1.8 we can use the trampoline capability of closures to overcome this problem.

We invoke a trampoline() method on a closure and our original closure is now wrapped in TrampolineClosure instance. Calls to the TrampolineClosure are executed sequentially invoking the original closure, until the original closure returns something else then a TrampolineClosure instance. This way the stack isn't filled and we won't get the stack overflow exceptions.

def sizeList
sizeList = { list, counter = 0 ->
    if (list.size() == 0) {
        counter
    } else {
        sizeList.trampoline(list.tail(), counter + 1)
    }
}
sizeList = sizeList.trampoline()

assert sizeList(1..10000) == 10000

Try with Groovy web console.

April 27, 2011

Groovy Goodness: Chain Closures Together with Closure Composition

There are a lot of new features in Groovy 1.8. One of them is the possibility to compose a new closure by chaining two other closures together. We use the leftShift and rightShift operators (<< and >>) to combine multiple closures to create a new closure.

def convert = { new Expando(language: it) }
def upper = { it.toUpperCase() }

// Composition.
def upperConvert = convert << upper

def languages = ['Groovy', 'Scala', 'Clojure'].collect(upperConvert)
println languages // Output: [{language=GROOVY}, {language=SCALA}, {language=CLOJURE}]
assert languages[0].language == 'GROOVY'
assert languages[1].language == 'SCALA'
assert languages[2].language == 'CLOJURE'

// Reverse composition.
def lastLetter = { it[-1] }
def firstLetters = ['Groovy', 'Clojure', 'Scala'].collect(upper >> lastLetter)
assert firstLetters.join() == 'YEA'

Try with Groovy web console.

December 1, 2010

Groovy Goodness: Invoke Anonymous Closure

Groovy closures can be invoked directly after we have defined them. This way we get the result immediately and can assign it to a variable. We use call() or () after we have defined the closure, so the closure code is executed and the return value of the closure is assigned to the variable.

def date = {
    def d = new Date()
    d.set year: 2010, month: Calendar.DECEMBER, date: 1
    d.format "dd-MM-yyyy"
}()

assert date == '01-12-2010'

def text = {
    def result = ''
    "mrhaki".size().times {
        result += it
    }
    result
}.call()

assert text == '012345'

April 19, 2010

Groovy Goodness: New Ways to Curry

A couple of weeks ago I gave a presentation about Groovy and the subject of closures and the curry() method was covered. Someone from the audience asked if the arguments could be 'curried' from right to left instead of from left to right. I had to say no, but since Groovy 1.7.2 this isn't true anymore. Groovy 1.7.2 adds the rcurry() method which uses a right to left order. And as a bonus we also have got the ncurry() method where we can supply a parameter value for an argument of the closure at a specific index.

@Grab('commons-lang:commons-lang:2.5')
import org.apache.commons.lang.RandomStringUtils as RSU

def randomClosure = { size, letters, numbers ->
    // Invoke RandomStringUtils.random() method 
    RSU.random size, letters, numbers
}

def randomNumbers = randomClosure.rcurry(false, true)  // letters = false, numbers = true
def randomLetters = randomClosure.ncurry(1, true, false) // letters = true, numbers = false

println randomClosure(10, true, true)  // Sample output: VG7mffNAdA
println randomNumbers(10)              // Sample output: 8099670444
println randomLetters(10)              // Sample output: ZOHlHewEPU

December 3, 2009

Groovy Goodness: Implicit Method doCall in Closure

After reading Mixing dynamic and static code in Groovy I learned about the implicit method available in a closure: doCall(). This method corresponds to the arguments and body of the closure. If we invoke a closure with the call() or the unnamed () syntax the doCall() method is invoked. We can use this method to run the closure from within the closure.

def sizeList = { list, counter = 0 ->
    if (list.size() == 0) {
        counter
    } else {
        doCall(list.tail(), counter + 1)  // Call closure self.
    }
}

assert 5 == sizeList([1,2,3,4,5])

November 28, 2009

Groovy Goodness: Closure Arguments

If we define a closure in Groovy we can define our own arguments or rely on the default it for a single argument closure. The it argument is available if we don't define any named arguments ourselves. We can also create a closure and define it to have no arguments even not the it argument.

// Closure with default 'it' argument.
def defaultIt = { it - 1 }
assert 'Groovy String with .' == defaultIt('Groovy String with 1.')
assert 41 == defaultIt(42)

// Closure with named argument.
def namedArg = { value -> value * 2 }
assert 'Groovy Groovy ' == namedArg('Groovy ')
assert 84 == namedArg(42)

// Closure with multiple named arguments.
def moreArgs = { a, b -> a + b }
assert 'Groovy Java' == moreArgs('Groovy ', 'Java')
assert 44 == moreArgs(42, 2)

// Closure without arguments, even no 'it'.
def noArgs = {-> 'Groovy closure without arguments' }
assert 'Groovy closure without arguments' == noArgs()

November 24, 2009

Groovy Goodness: Setting a Closure's Delegate

Closures are reusable code blocks in Groovy. The code of the closure is executed against the delegate of the closure. By default the owner of the closure is the same as the delegate, but we can change this. We can define which object is the delegate for a closure, so we can change the object the closure is executed for.

// Simple class.
class Post {
    int count
    def info() { "This is Groovy Goodness post #$count!" }
}

// Script variable and method.
count = 0
def info() {
    "Count value is $count."
}

// Closure to increment a count variable and invoke a info() method.
def printInfo = { 
    count++
    info() 
}

assert "Count value is 1." == printInfo() // Delegate is by default set to owner, so the script in this case.

printInfo.resolveStrategy = Closure.DELEGATE_FIRST  // Change closure resolver so first the delegate is used.
printInfo.delegate = new Post(count: 100)  // Set delegate to Post object.
assert "This is Groovy Goodness post #101!" == printInfo()

November 12, 2009

Groovy Goodness: Passing Closures to Methods

Closures are blocks of code we can assign to variables and pass around like objects. We can use closures as method arguments, but we must make sure we use the correct syntax. Groovy has some variations we can use to pass a closure into a method. If for example the closure is the last argument for a method we can put the closure outside the argument list.

// Method with two arguments. Last argument is a closure.
def work(input, cl) {
    cl(input)
}

// Define a closure.
def assertJava = {
    it == 'Java'
}

work('Java', assertJava)

work 'Java', assertJava  // No parenthesis.

work('Groovy', {
    assert it == 'Groovy' 
})  // Anonymous closure as argument.

work('Groovy') {
    assert it == 'Groovy'
}  // Last argument is closure and can be outside parenthesis.

work('Groovy')
{
     assert it == 'Groovy'
}  // Opening bracket on new line. If we want a code block (e.g. static initializer) instead of closure we must use ; to separate code.


work 'Groovy', {
    assert it == 'Groovy'
}  // Pay attention, no parenthesis, so comma is needed again!


// Does not work:
//
// Comma between argument list needed:
// work 'Groovy' {
//     assert it == 'Groovy'
// }

September 7, 2009

Groovy Goodness: Add Some Curry for Taste

Currying is a technique to create a clone of a closure and fixing values for some of the parameters. We can fix one or more parameters, depending on the number of arguments we use for the curry() method. The parameters are bound from left to right. The good thing is we can even use other closures as parameters for the curry() method.

Let's see some curry() action in the following sample:

// Simple sample.
def addNumbers = { x, y -> x + y }
def addOne = addNumbers.curry(1)
assert 5 == addOne(4)


// General closure to use a filter on a list.
def filterList = { filter, list -> list.findAll(filter) }
// Closure to find even numbers.
def even = { it % 2 == 0 }
// Closure to find odd numbers.  
def odd = { !even(it) }  
// Other closures can be curry parameters.
def evenFilterList = filterList.curry(even)
def oddFilterList = filterList.curry(odd)
assert [0,2,4,6,8] == evenFilterList(0..8)
assert [1,3,5,7] == oddFilterList(0..8)


// Recipe to find text in lines.
def findText = { filter, handler, text -> 
    text.eachLine {
        filter(it) ? handler(it) : null
    }
}
// Recipe for a regular expression filter.
def regexFilter = { pattern, line -> line =~ pattern }

// Create filter for searching lines with "Groovy".
def groovyFilter = regexFilter.curry(/Groovy/)
// Create handler to print out line.
def printHandler = { println "Found in line: $it" }

// Create specific closure as clone of processText to
// search with groovyFilter and print out found lines.
def findGroovy = findText.curry(groovyFilter, printHandler)

// Invoke the closure.
findGroovy('''Groovy rules!
And Java?
Well... Groovy needs the JVM... 
''')

// This will output:
// Found in line: Groovy rules!
// Foudn in line: Well... Groovy needs the JVM...

Run this script on GroovyConsole.