...
| Code Block |
|---|
def gcd //predefine closure name
gcd={ m,n-> m%n==0? n: gcd(n,m%n) }
assert gcd( 28, 35 ) == 7
|
We can even make a recursion of anonymous closures (thanks to 'call' method available for each closure)
| Code Block |
|---|
def results = [];
{ a, b ->
results << a
a<10 && call(b, a+b)
}(1,1)
assert results == [1, 1, 2, 3, 5, 8, 13] // Fibonacci numbers
|
Functions
A function is similar to a closure, though a function can't access defined variables in its surrounding context:
...