2011-10-09 46 views
3

比方说,我有一个封闭:如何使用groovy集合的collect()方法调用多个参数的闭包?

def increment = {value, step -> 
    value + step 
} 

现在我想遍历我整数集合的每一个项目,用5增加它,并保存新的元素,新的集合:

def numbers = [1..10] 
def biggerNumbers = numbers.collect { 
     it + 5 
} 

现在我想达到相同的结果,但通过使用increment关闭。我怎样才能做到这一点?

应该是这样的(如下错误代码):

def biggerNumbers = numbers.collect increment(it, 5) //what's the correct name of 'it'?? 

回答

10

你的问题的解决方案将被筑巢的增量中的呼叫终止:

def biggerNumbers = numbers.collect {increment(it, 5)} 

如果你想通过预制关闭到collect你应该使它与collect兼容 - 接受单个参数即:

def incrementByFive = {it + 5} 
def biggerNumbers = numbers.collect incrementByFive 
9

mojojojo有正确的答案,但只是以为我想补充的是,这看起来像一个很好的候选人currying(特别using rcurry

如果您有:

def increment = {value, step -> 
    value + step 
} 

然后可以咖喱权具有这种功能的 - 手参数:

def incrementByFive = increment.rcurry 5 

然后,你可以这样做:

def numbers = 1..10 
def biggerNumbers = numbers.collect incrementByFive 

只是认为这可能会感兴趣;-)

+0

感谢,这是非常有趣的。 – Roman

+0

有趣的建议,但是当'numbers.collect incrementByFive'已经足够时,通过实例化一个冗余闭包,你在'numbers.collect {incrementByFive it}'中犯了一个小错误。像这样的事情会导致开销,尽管Groovy并不关心性能。 –

+0

@mojojojo良好的感谢感谢:-)修正了代码,因为没有为未来的人提供次优例子:-) –

0

的主要问题是,[1..10]创建List<IntRange>你试图递增。你应该collect在IntRange直接(注意缺少括号):

(1..10).collect { it + 5 } 

或者咖喱:

def sum = { a, b -> a + b } 
(1..10).collect(sum.curry(5)) 
相关问题