我想實現一個Scala宏,該宏使用部分函數,對函數的模式執行一些轉換,然後將其應用於給定的表達式。如何使用Scala宏來轉換和應用部分函數?
要做到這一點,我開始用下面的代碼:
def myMatchImpl[A: c.WeakTypeTag, B: c.WeakTypeTag](c: Context)(expr: c.Expr[A])(patterns: c.Expr[PartialFunction[A, B]]): c.Expr[B] = {
import c.universe._
/*
* Deconstruct the partial function and select the relevant case definitions.
*
* A partial, anonymus function will be translated into a new class of the following form:
*
* { @SerialVersionUID(0) final <synthetic> class $anonfun extends scala.runtime.AbstractPartialFunction[A,B] with Serializable {
*
* def <init>(): anonymous class $anonfun = ...
*
* final override def applyOrElse[...](x1: ..., default: ...): ... = ... match {
* case ... => ...
* case (defaultCase$ @ _) => default.apply(x1)
* }
*
* def isDefined ...
* }
* new $anonfun()
* }: PartialFunction[A,B]
*
*/
val Typed(Block(List(ClassDef(a, b, x, Template(d, e, List(f, DefDef(g, h, i, j, k, Match(l, allCaseDefs)), m)))), n), o) = patterns.tree
/* Perform transformation on all cases */
val transformedCaseDefs: List[CaseDef] = allCaseDefs map {
case caseDef => caseDef // This code will perform the desired transformations, now it's just identity
}
/* Construct anonymus partial function with transformed case patterns */
val result = Typed(Block(List(ClassDef(a, b, x, Template(d, e, List(f, DefDef(g, h, i, j, k, Match(l, transformedCaseDefs)), m)))), n), o)
// println(show(result))
c.Expr[B](q"$result($expr)")
}
我解構了部分功能,選擇applyOrElse功能的情況下定義,執行每個定義所需的改造,並把一切重新走到一起。這個宏是這樣調用的:
def myMatch[A, B](expr: A)(patterns: PartialFunction[A, B]): B = macro myMatchImpl[A,B]
不幸的是,這並不像預期的那樣工作。在一個簡單的例子在下面的錯誤消息使用宏
def test(x: Option[Int]) = myMatch(x){
case Some(n) => n
case None => 0
}
結果:
object creation impossible, since method isDefinedAt in trait PartialFunction of type (x: Option[Int])Boolean is not defined
這是有點混亂,因爲打印生成的部分功能產量
({
final <synthetic> class $anonfun extends scala.runtime.AbstractPartialFunction[Option[Int],Int] with Serializable {
def <init>(): anonymous class $anonfun = {
$anonfun.super.<init>();
()
};
final override def applyOrElse[A1 <: Option[Int], B1 >: Int](x2: A1, default: A1 => B1): B1 = ((x2.asInstanceOf[Option[Int]]: Option[Int]): Option[Int] @unchecked) match {
case (x: Int)Some[Int]((n @ _)) => n
case scala.None => 0
};
final def isDefinedAt(x2: Option[Int]): Boolean = ((x2.asInstanceOf[Option[Int]]: Option[Int]): Option[Int] @unchecked) match {
case (x: Int)Some[Int]((n @ _)) => true
case scala.None => true
case (defaultCase$ @ _) => false
}
};
new $anonfun()
}: PartialFunction[Option[Int],Int])
這清楚地定義了isDefinedAt方法。
有沒有人有一個想法,這裏有什麼問題,以及如何做到這一點?
這不是您問題中最有趣的部分的答案,但您是否嘗試過使用['Transformer'](http://www.scala-lang.org/api/current/index.html#scala.reflect .api.Trees $變壓器)?它應該[做你想做的](https://gist.github.com/travisbrown/6340753),可能更強大。 –
@TravisBrown Transformer類正是我一直在尋找的,謝謝你的提示。隨意發佈你的要點作爲答案。 –