2014-02-15 40 views
1

我試圖保存用於在Scala中排序序列的參數,以便稍後推遲執行。Scala保存排序函數參數

例如,我想保存(「.value」)排序函數,而不是「list.sortBy(.value)」,並在稍後檢索此排序函數(「_.value」)實際分揀的時間。

如何保存並檢索延遲執行的排序函數參數?下面是一些樣本測試代碼:

class SortTest { 

    def testSort() = { 

    val myClass = new MyClass(0) 
    val list = List (myClass, new MyClass(1), new MyClass(2), new MyClass(3), new MyClass(4)) 

    // Want to sort by value attribute, but don't want to sort right away. Rather 
    // how do I save the sort function, and retrieve it at a later time for execution? 
    list.sortBy(_.value) 

    // save the sort function (i.e. sort by the value attribute of myClass) 
    // something similar to the following syntax 
    myClass.setSortFunction (_.value) 

    // retrieve the sort function and sort the list 
    list.sortBy(myClass.getSortFunction())   

    } 

    class MyClass (d:Int){ 
    val value = d 
    val sortFunc = null 

    // what should be the signature of this function ? 
    def setSortFunction (sortFunc:()) = { 
     this.sortFunc = sortFunc 
    } 

    // what should be the return type of this function? 
    def getSortFunction() = { 
     return sortFunc 
    } 

    } 

} 
+1

爲什麼不把這個函數分配給變量?你爲什麼不使用懶惰的集合?你想通過推遲排序來完成什麼? –

回答

1

你可以做這樣的事情:

val sortFunction = (x : { def value: Int }) => x.value 

在這一點上,你可能不會滿意的Int的硬編碼。不幸的是,功能必須有明確定義的類型,所以我不能在返回類型上使這個泛型。

一個可以代替使一個定義:

def sortFunction[T] = (x : { def value: T }) => x.value 

但是,你不能傳遞定義身邊,只值和值不能進行參數設置。

另一方面,你正在接近這個錯誤的方式 - 有一個假設,sortBy採取一個函數作爲參數,只有這一點。不正確:sortBy需要兩個參數:一個函數和一個Ordering。如果您不保存排序,則無法排序。

在這裏我們得到另一個問題...函數必須有一個類型MyClass => T,並且排序必須是Ordering[T]類型。事先不知道什麼是T,你不能保存。

幸運的是,爲什麼Ordering是一個好主意,您可以簡單地創建一個Ordering[MyClass],並使用它!

方法如下:

class MyClass(d: Int) { 
    val value = d 
    private var sortFunction: Ordering[MyClass] = _ 
    def setSortFunction[T : Ordering](f: MyClass => T) { 
    sortFunction = Ordering by f 
    } 
    def getSortFunction = sortFunction 
} 

並且你使用這樣的:這不是sortBy它採用sorted

list.sorted(myClass.getSortFunction) 

通知。方法sortBy通過創建Ordering並調用sorted來實現,因此您不會失去任何性能。