代码之家  ›  专栏  ›  技术社区  ›  svrist

复制scala中的对象,但更改“子对象”进行重写

  •  1
  • svrist  · 技术社区  · 15 年前

    kiama 一种通用的“dup”方法 is defined 哪些副本 Product 对象,并将给定函数应用于 产品 为了支持重写 Term S:

    /**
     * General product duplication function.  Returns a product that applies
     * the same constructor as the product t, but with the given children            
     * instead of t's children.  Fails if a constructor cannot be found or
     * if one of the children is not of the appropriate type.
     */
    private def dup (t : Product, children : Array[AnyRef]) : Product = {
    
        val ctor = (t.getClass.getConstructors())(0)
        try {
            val ret = ctor.newInstance (children : _*).asInstanceOf[Product]
            ret
                                                                                        } catch {
            case e : java.lang.ClassCastException =>
                error ("dup cast failed: " + t)
            case e : IllegalArgumentException =>
                error ("dup illegal arguments: " + ctor + " (" +
                       children.deep.mkString (",") + "), expects " +
                       ctor.getParameterTypes.length)
        }            
    }
    

    使用 like this :

    private def childProduct (p : Product, i : Int, s : => Strategy) : Option[Term] = {
        val numchildren = p.productArity
        val ct = p.productElement (i-1)
        val children = new Array[AnyRef](numchildren)
        for (j <- 0 until numchildren)
           children (j) = makechild (p.productElement (j))
           s (ct) match {
                    case Some (ti) =>
                        children (i-1) = makechild (ti)
                    case None      =>
                        return None
               }
        val ret = dup (p, children)
        Some (ret)
    

    这给了一些使用上的限制。 我知道他们正在努力更换这个机构( Issue 2 , Issue 31 )但我觉得听到你们会怎么做可能很有趣?

    例如, Positional var(或任何其他var!)不复制scala解析器组合器的。事实上,所有内容都不是explict第一个构造函数的一部分(因此也就是默认编译器生成的 unapply 方法)。

    我一直在尝试提供某种特性或类似的特性,我可以在我的术语中添加dup/childproduct/etc方法可以使用的特性,但还没有运气。(我不知道凯斯班怎么样) copy 可以使用)

    2 回复  |  直到 15 年前
        1
  •  1
  •   Randall Schulz    15 年前

    RSchulz/sbtr Rewriter.scala

    • src/main/scala/rrs/sbtr/SBTR.scala
    • src/main/scala/rrs/sbtr/RewriterFmt.alacs
    • src/main/scala/rrs/sbtr/Rewriter-0.8.alacs
    • src/main/scala/rrs/sbtr/Rewriter.alacs

    queryf SBTR

    .alacs

        2
  •  3
  •   Randall Schulz    15 年前

    Rewriter Constructable deconstruct reconstruct dup child all some construct

    Product

    (最后,我添加了一个优化,如果子值(非原子值)的转换结果都与原始值相同,则可以避免生成新值。我只在处理 可构造的 美国)