Groovy闭包

xiaoxiao2021-03-01  8

Groovy闭包

def factorial = [ 2 , 3 , 4 , 5 ].inject( 1 ){previous,element -> previous * element}println " Factorial(5):\${factorial} "

－－－－－－－－－－－结果：Factorial(5): 120－－－－－－－－－－－

deffact = 1 [ 2 , 3 , 4 , 5 ] . each {number -> fact *= number}println " fact:\${fact} "

－－－－－－－－－－－结果：fact: 120－－－－－－－－－－－

def list = [ 2 , 3 , 4 , 5 ]factorial = list.inject( 1 ){previous,element -> previous * element}println " Factorial(5):\${factorial} "

－－－－－－－－－－－结果：Factorial(5): 120－－－－－－－－－－－

list = [ 2 , 3 , 4 , 5 ] def closure = {previous,element -> previous * element}factorial = list.inject( 1 ,closure)println " Factorial(5):\${factorial} "

－－－－－－－－－－－结果：Factorial(5): 120

// Findthoseitemsthatqualify def filter(list,predicate){ return list.findAll(predicate)} // Twopredicateclosure def isEven = {x -> return (x % 2 == 0)} def isOdd = {x -> return !isEven(x)} def table = [ 11 , 12 , 13 , 14 ] // Applyfilter def evens = filter(table,isEven)println " evens:\${evens} " def odds = filter(table,isOdd)println " odds:\${odds} "

－－－－－－－－－－－结果：evens: [12, 14]odds: [11, 13]

// Findinitiallistthatconformstopredicate def takeWhile = {predicate,list -> def result = [] for (element in list){ if (predicate(element)){result << element} else { return result}} return result} // Twopredicateclosures def isEven = {x -> return x % 2 == 0} def isOdd = {x -> return !isEven(x)} def table1 = [ 12 , 14 , 15 , 18 ] def table2 = [ 11 , 13 , 15 , 16 , 18 ] // ApplytakeWhile def evens = takeWhile.call(isEven,table1)println " evens:\${evens} " def odds = takeWhile.call(isOdd,table2)println " odds:\${odds} "

－－－－－－－－－－－－结果：evens: [12, 14]odds: [11, 13, 15]

def multiply(x){ return {y -> return x * y}} def twice = multiply( 2 )println " twice(4):\${twice(4)} " // Closurereturningaclosure def multiplication = {x -> return {y -> return x * y}} def quadruple = multiplication( 4 )println " quadruple(3):\${quadruple(3)} "