How can one match an array with quotes using Varargs? #20550
-
I posted this question in the Discord meta-programming channel, and have had no luck. So I am trying here. Assume I have the following code: val s1 = ConstArray.testUnapply(Array(1, 2, 3)) I would like to match that array in the (x: Expr[Array[T]]) match
case '{ scala.Array.apply($a:Int, $b:Int, $c:Int): scala.Array[Int]} =>
println(s"(a, b, c) = ($a, $b, $c)")
??? However, I need to deal with a variable number of arguments. So I tried many variations that include: case '{ scala.Array.apply(${Varargs(Exprs(elems))}: Seq[Int])} =>
=>
Some(Array(elems*).asInstanceOf[Array[T]])
??? None of these work. I have also noticed that the following fails: case '{ scala.Array.apply[Int]($a:Int, $b:Int, $c:Int): scala.Array[Int]} =>
println(s"(a, b, c) = ($a, $b, $c)")
??? Why does this fail? Do I have to add something related to to val fct = summon[FromExpr[ClassTag[Int]]]
(x: Expr[Array[T]]) match
case '{ scala.Array.apply( ${varArgs} : Expr[Seq[Int]])(using $fct) } =>
???
Any help appreciated. TIA |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I started an answer on the forum https://users.scala-lang.org/t/scala-3-macros-quotes-how-to-match-scala-array-1-2-3/10046/2?u=som-snytt. I'll follow up here with more code. Arguably code looks better on github. |
Beta Was this translation helpful? Give feedback.
-
The answer was that since the signatures for
or matching on the tree shape
|
Beta Was this translation helpful? Give feedback.
The answer was that since the signatures for
Array.apply
are specialized for primitives, it's necessary to match on those signatures.or matching on the tree shape