Skip to content

Instantly share code, notes, and snippets.

@xeno-by
Created January 15, 2013 21:46
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xeno-by/4542402 to your computer and use it in GitHub Desktop.
Save xeno-by/4542402 to your computer and use it in GitHub Desktop.
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