Extraction of Tuple1 in comparison of quasi-quasotes
Suppose I want a macro that takes an expression and returns arity if it is a string literal. Something like this works for tuples, but returns Some(1)
instead None
for everything else:
import scala.reflect.macros.blackbox.Context
class ArityMacros(val c: Context) {
import c.universe._
def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match {
case q"(..$xs)" => q"_root_.scala.Some(${ xs.size })"
case _ => q"_root_.scala.None"
}
}
import scala.language.experimental.macros
def arity[A](a: A): Option[Int] = macro ArityMacros.arity[A]
I know I can do something like this:
class ArityMacros(val c: Context) {
import c.universe._
def arity[A: c.WeakTypeTag](a: c.Expr[A]): c.Tree = a.tree match {
case q"scala.Tuple1.apply[$_]($_)" => q"_root_.scala.Some(1)"
case q"(..$xs)" if xs.size > 1 => q"_root_.scala.Some(${ xs.size })"
case other => q"_root_.scala.None"
}
}
But feel like there must be a better way to distinguish between cases Tuple1
and non-tuples (and maybe I've used it in the past?).
+3
source to share
No one has answered this question yet
Check out similar questions: