Skip to content

How can one match an array with quotes using Varargs? #20550

Closed Answered by som-snytt
hmf asked this question in Metaprogramming
Discussion options

You must be logged in to vote

The answer was that since the signatures for Array.apply are specialized for primitives, it's necessary to match on those signatures.

def _arraylen(xs: Expr[Array[?]])(using Quotes): Expr[Int] =
  xs match
  //case '{ Array(${_}: A, (${Varargs(elems)}: Seq[A])*) } => Expr(elems.length + 1)
  case '{ Array(${_}: Int, (${Varargs(elems)}: Seq[Int])*) } => Expr(elems.length + 1)
  case '{ Array[a]((${Varargs(elems)}: Seq[a])*)($_) } => Expr(elems.length)
  case _ => Expr(-1)

or matching on the tree shape

def _arraylen(xs: Expr[Array[?]])(using Quotes): Expr[Int] =
  import quotes.reflect.*
  xs match
  case '{ Array[a]((${Varargs(elems)}: Seq[a])*)($_) } => Expr(elems.length)
  case _ =>
   …

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by hmf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants