Programming Tricks
Groovy Tricks
Polynomial and polynomial functions using closures
Use closures for fast writting of well readable code!
/*
* Using closure functions for easy and readable expression
* of (even complex) symbolic constructs
*
* Closures are functions considered as first-class objects,
* we can store them to variables thus give them symbolic names
* for further reuse
*
* Tomas Pitner, tomp at fi dot muni dot cz
* Version 1.0, Jan 30 2008
*
*/
def term = { a, func ->
return {x-> a * func(x)}
}
def polynomial = { terms ->
// create and return the polynomial function for the polynomial
// composed of the given terms
{ x ->
double total = 0;
// for each term, add its result to the total
// implicit parameter it is used in the closure in 'each'
terms.each { total += it(x)}
return total;
}
}
def constant = { p -> 1 } // or constant = { 1 }
def linear = { p -> p } // or linear = { it }
def square = { p -> p * p } // or square = { it * it }
// p(x) = 3*x^2 + 10*x + 20
p = polynomial([term(3, square), term(10, linear), term(20, constant)])
println "value of the polynomial function p for 0 is " + p(0)
println "value of the polynomial function p for 1 is " + p(1)
println "value of the polynomial function p for 2 is " + p(2)
println "value of the polynomial function p for 3 is " + p(3) + "\n"
// the terms of the same order may appear multiple times in one polynomial
q = polynomial([term(3, square), term(10, square), term(20, constant)])
println "value of the polynomial function q for 0 is " + q(0)
println "value of the polynomial function q for 1 is " + q(1)
println "value of the polynomial function q for 2 is " + q(2)
println "value of the polynomial function q for 3 is " + q(3)
if it cannot be copied into the clipboard or you want the full NetBeans6.5 project, click to
GroovyPolynomial.zip.