我是Groovy的新手。我想把接线员当作函数传递。
而不是:
nums.inject(0) { acc, el -> acc * el }我想做这样的事情:
nums.inject(0) {*}在F#中,这是可能的。Groovy提供了相同的语法糖吗?
let product = List.reduce (*) nums 0发布于 2015-10-20 17:14:50
运算符不允许传递,但函数/闭包是等价的。
def product = nums.inject(1, Math.&multiplyExact)
inject有两个参数,一个对象和一个闭包。您的示例定义了自己的闭包,但是可以使用方法指针操作符(.&)将方法引用为闭包
在括号外放置一个文字闭包,{ }是一个小的语法糖,对于方法调用的最后一个参数的任何闭包都可以这样做。
发布于 2015-10-20 16:42:19
我不这样认为。但是,您可以使用一些元编程来接近。
/*
* Creates the method Collection.reduce(Object, Closure).
* Unlike Collection.inject(Object, Closure), this method
* expects a closure with a single argument: the
* current element in the collection. The closure is
* re-created to run with the accumulated value as the
* owner and then called with the current element as the argument.
*/
Collection.metaClass.reduce = { Object initial, Closure closure ->
delegate.inject(initial) { acc, obj ->
closure.rehydrate(acc, acc, acc)(obj)
}
}
def nums = [1, 2, 3]
/*
* Number.&multiply returns the Number.multiply(Number) method
* as a Closure.
*/
def result = nums.reduce(1, Number.&multiply)
assert result == 6为了让您更好地了解reduce(Object, Closure)方法的工作原理,还有一种方法可以使用它:
nums.reduce(1) { num -> multiply(num) }闭包的唯一参数是当前元素。因为所有方法调用和属性访问都委托给累加器,所以multiply(Number)方法对累加器:acc.multiply(num)执行。
https://stackoverflow.com/questions/33240970
复制相似问题