0

有没有办法提取或询问部分应用的函数以获得应用的值。例如,可以从下面代码中的reduceBy3中提取值3。

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

我已经尝试创建一个提取器,如下例所示,但是 unapply 方法必须接受一个需要询问的 (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)
}
4

2 回答 2

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))
}
于 2013-10-13T05:11:09.707 回答
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
    }
  }
}
于 2013-10-12T04:34:17.343 回答