Created
January 15, 2013 21:46
-
-
Save xeno-by/4542402 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import language.experimental.macros | |
import language.implicitConversions | |
import scala.reflect.macros.Context | |
import scala.reflect.runtime.universe.Tree | |
class ReflectiveClosure[A, B](val tree: Tree, fn: Function1[A, B]) extends Function1[A, B] { | |
def apply(x: A) = fn(x) | |
} | |
object ReflectiveClosure { | |
implicit def reflectClosure[A, B](f: Function1[A,B]): ReflectiveClosure[A, B] = macro Macros.reflectiveClosureImpl[A, B] | |
} | |
object Macros { | |
def reflectiveClosureImpl[A, B](c: Context)(f: c.Expr[Function1[A, B]]) = { | |
import c.universe._ | |
val u = treeBuild.mkRuntimeUniverseRef | |
val m = EmptyTree | |
val tree = c.Expr[scala.reflect.runtime.universe.Tree](Select(c.reifyTree(u, m, f.tree), newTermName("tree"))) | |
c.universe.reify(new ReflectiveClosure(tree.splice, f.splice)) | |
} | |
} | |
======== | |
object Test extends App { | |
implicit class PimpedList[T](val list: List[T]) { | |
def query(predicate: ReflectiveClosure[T, Boolean]): List[T] = { | |
println(predicate.tree) | |
list filter predicate | |
} | |
} | |
List(1, 2, 3).query((x: Int) => x % 2 == 0) | |
} | |
======== | |
22:45 ~/Projects/Kepler_macrosnippet01/sandbox (topic/macrosnippet01)$ scalac Macros.scala && scalac Test.scala && scala Test | |
((x: Int) => x.$percent(2).$eq$eq(0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment