Scala 3:创建 Expr[ Int => Int ]

Scala 3 : Create Expr[ Int => Int ]

我在一个项目中使用 Scala3 宏,但我一直在创建函数的 Expr(和 ToExpr)。

我有这样的东西:

case class Foo(f : Int => Int)

given ToExpr[Foo] with {
    def apply(foo : Foo) = foo match {
        case Foo(f) => '{Foo(???)} // <-- here
    }
}

我不知道如何用 Expr[Int => Int] 替换上面的 ???


编辑:这是@GaelJ

的一些失败尝试

1) 先试试

def apply(foo : Foo) = foo match {
  case Foo(f) =>
    val ff: Expr[Int => Int] = '{ (x: Int) => f.apply(x) }
    '{Foo($ff)}
}

给出:

|        val ff: Expr[Int => Int] = '{ (x: Int) => f.apply(x) }
|                                                  ^
|                             access to value f from wrong staging level:
|                              - the definition is at level 0,
|                              - but the access is at level 1.

2) 第二次尝试

def apply(foo : Foo) = foo match {
  case Foo(f) =>
    val ff: Expr[Int => Int] = '{ (x: Int) => ($f).apply(x) }
    '{Foo($ff)}
}

给出:

|        val ff: Expr[Int => Int] = '{ (x: Int) => ($f).apply(x) }
|                                                    ^
|                                              Found:    (f : Int => Int)
|                                              Required: quoted.Expr[Any]

这里是 given 构建新 ToExpr 的“积木”:scala3 docs ToExpr。据我所知,不可能为函数构造 ToExpr