2015-10-20 19 views
1

我是Groovy的新手。我想通過一個運算符作爲函數。傳遞一個運算符作爲函數

相反的:

nums.inject(0) { acc, el -> acc * el } 

我想這樣做:

nums.inject(0) {*} 

在F#中,這是可能的。 Groovy是否提供相同的語法糖?

let product = List.reduce (*) nums 0 
+0

據我所知在groovy中是不可能的。 – Opal

+0

我不相信它...... –

回答

2

運營商不允許周圍通過,但功能/封閉件,因此或多或少等效

def product = nums.inject(1, Math.&multiplyExact)

inject採用兩個參數,一個對象和一個閉合。你的榜樣定義了自己的關閉,但它可能參考方法爲使用method pointer operator (.&)

把一個文字關閉,該{ }封鎖,外面的括號是可以對任何閉包是一種方法做了一些語法糖電話的最後一個參數。

1

我不這麼認爲。但是,你可以接近一些元編程。

/* 
* 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)

相關問題