6

我想知道 Scala 是否支持递归宏扩展,例如我正在尝试编写一个带有镜头宏的镜头库来执行此操作:

case class C(d: Int)
case class B(c: C)
case class A(b: B)

val a = A(B(C(10))
val aa = lens(a)(_.b.c.d)(_ + 12)
assert(aa.b.c.d == 22)

鉴于lens(a)(_.b.c.d)(f),我想将其转换为a.copy(b = lens(a.b)(_.c.d)(f))

编辑: 我在这里取得了一些不错的进展

List[TermName]但是,对于上面的示例,我无法找出创建访问器的通用方法,因为我有List(TermName('b'), TermName('c'), TermName('d'))),我想生成一个匿名函数,_.b.c.d(x: A) => x.b.c.d。我怎么做?

基本上,我怎样才能以通用的方式编写这些行?

4

1 回答 1

3

实际上我设法使它工作:https ://github.com/pathikrit/sauron/blob/master/src/main/scala/com/github/pathikrit/sauron/package.scala

这是完整的来源:

package com.github.pathikrit

import scala.reflect.macros.blackbox

package object sauron {

  def lens[A, B](obj: A)(path: A => B)(modifier: B => B): A = macro lensImpl[A, B]

  def lensImpl[A, B](c: blackbox.Context)(obj: c.Expr[A])(path: c.Expr[A => B])(modifier: c.Expr[B => B]): c.Tree = {
    import c.universe._

    def split(accessor: c.Tree): List[c.TermName] = accessor match {    // (_.p.q.r) -> List(p, q, r)
      case q"$pq.$r" => split(pq) :+ r
      case _: Ident => Nil
      case _ => c.abort(c.enclosingPosition, s"Unsupported path element: $accessor")
    }

    def join(pathTerms: List[TermName]): c.Tree = (q"(x => x)" /: pathTerms) {    // List(p, q, r) -> (_.p.q.r)
      case (q"($arg) => $pq", r) => q"($arg) => $pq.$r"
    }

    path.tree match {
      case q"($_) => $accessor" => split(accessor) match {
        case p :: ps => q"$obj.copy($p = lens($obj.$p)(${join(ps)})($modifier))"  // lens(a)(_.b.c)(f) = a.copy(b = lens(a.b)(_.c)(f))
        case Nil => q"$modifier($obj)"                                            // lens(x)(_)(f) = f(x)
      }
      case _ => c.abort(c.enclosingPosition, s"Path must have shape: _.a.b.c.(...), got: ${path.tree}")
    }
  }
}

而且,是的,Scala 确实递归地应用了相同的宏。

于 2015-03-03T11:26:03.553 回答