2013-10-12 62 views
0

有沒有辦法提取或詢問部分應用函數以獲取應用值。 例如,可以從下面的代碼中的reduceBy3中提取值3。部分應用函數是否可以提取或詢問應用參數值

def subtract(x:Int, y:Int) = x-y 
val reduceBy3 = subtract(3,_:Int) 

我已經與創建的提取實驗已經顯示在下面但是取消應用方法必須接受需要詢問一個(INT =>內部)函數的例子。

class ReduceBy(y: Int) { 
    val amt = y 
    def subtract(y: Int, x: Int) = x - y 
} 

object ReduceBy extends Function1[Int, Int => Int] { 
    def apply(y: Int) = { 
    val r = new ReduceBy(y) 
    r.subtract(y, _: Int) 
    } 
    def unapply(reduceBy: ReduceBy): Option[Int] = Some(reduceBy.amt) 
} 

object ExtractPartialApplied extends App { 
    val r3 = ReduceBy(3) 
    val extract = r3 match { 
    case ReduceBy(x) => ("reduceBy", x) 
    case x: ReduceBy => ("reduceBy", x.amt) 
    case _ => ("No Match", 0) 
    } 

    println(extract) 
    val z = r3(5) 
    println(z) 
} 

回答

0

你可以有你subtract方法獲得的第一個參數,然後返回函數樣的對象,然後將採取的第二個參數,類似於多參數列表的功能,但它那麼你可以擴展但是你希望。

雖然這看起來不太優雅,並且需要一些手動樣板。

class ReduceBy(val amt: Int) { 
    def subtract(x: Int) = { 
    val xx = x // avoid shadowing 
    new Function[Int, Int] { 
     def x = xx 
     def apply(y: Int) = x - y 
    } 
    } 
} 
0

的溶液通過適配danielkza答案是有同伴對象做提取並返回保持到所述初始值的ReduceBy功能。

object ReduceBy { 
    def apply(y: Int) = new ReduceBy(y) 
    def unapply(reduceBy: ReduceBy): Option[Int] = Some(reduceBy.amt) 
}  

class ReduceBy(val amt: Int) extends Function[Int, Int] { 
    def apply(y: Int) = y - amt 
} 

object ExtractPartialApplied extends App { 
    val reduceBy3 = ReduceBy(3) 
    val extract = reduceBy3 match { 
    case ReduceBy(x) => ("ReduceBy(x)", x) 
    case x: ReduceBy => ("ReduceBy", x.amt) 
    case _ => ("No Match", 0) 
    } 
    println(extract) 
    println(reduceBy3(5)) 
} 
相關問題