【问题标题】:Polymorphic scala return type in recursive functions递归函数中的多态scala返回类型
【发布时间】:2013-11-18 22:37:14
【问题描述】:

我有一个树形结构:

sealed trait Tree
case class Node(l: Tree, r: Tree) extends Tree
case class Leaf(n: Int) extends Tree

还有一个修改树的函数:

def scale(n: Int, tree: Tree): Tree = tree match {
  case l: Leaf => Leaf(l.n * n)
  case Node(l, r) => Node(scale(n, l), scale(n, r))
}

上述方法的签名应该是什么才能返回适当的 Tree 子类型,并使以下行编译?

scale(100, Leaf(1)).n // DOES NOT COMPILE

到目前为止我找到的最接近的答案是here,并谈到了F-Bounded Quantification。但是我找不到将其应用于递归结构(例如树)的方法!有什么想法吗?

【问题讨论】:

  • 我不确定您所说的“适当的树子类型”是什么意思。我的猜测是创建def scale(n: Int, tree: Tree): Either[Tree,Node] 并将Leaf 和Node 值更改为Right(Leaf(...)) 和Left(Node(...))。使用这种方法,甚至可以消除模式匹配,因为参数中的也是一个。
  • 我认为在编译时无法从输入参数中确定scale 的结果类型。但是为什么要麻烦,您可以在比例结果上使用模式匹配来获得 n,这是一种常见的做法。 Either[Leaf, Node] 不会带来任何新的东西,因为您将匹配左/右而不是这只是一个冗余代码。

标签: scala recursion type-systems


【解决方案1】:

在 Scala 中,通常有两个选项可以为类型定义函数。一个更实用(像你一样使用模式匹配),另一个更面向对象。

不幸的是,对于带有模式匹配的版本,我没有解决方案(尽管我会对此感兴趣)。但我有一个更面向对象版本的解决方案,如果这是你的一个选项:

sealed trait Tree {
  def scale(n: Int): Tree
}
case class Node(l: Tree, r: Tree) extends Tree {
  def scale(n: Int): Node = Node(l.scale(n), r.scale(n))
}
case class Leaf(n: Int) extends Tree {
  def scale(m: Int): Leaf = Leaf(n * m) 
}

Leaf(1).scale(100).n // does compile.

这个方案是基于方法的返回类型是协变的,所以Node和Leaf中的scale的实现中的返回类型可以是抽象的返回类型的子类型Tree 中的方法 scale。

【讨论】:

    【解决方案2】:

    除了 OOP 和覆盖之外,还有另一个解决方案:

    您实际上可以定义一个类型类Scaler,它表示从(T, Int) 到T 的函数,其中T 是Tree 的子类型。在Scaler 的伴生对象中,您可以定义相应的隐式来完成实际工作。返回值的静态类型遵循类型类的定义。请注意,我使用两个通用参数扩展了您对 Node 的定义。可以通过使用抽象类型来替代。这留给读者作为练习:)

    好吧,我们开始吧:

    import language.implicitConversions
    
    sealed trait Tree
    case class Node[L <: Tree, R <: Tree](l: L, r: R) extends Tree
    case class Leaf(n: Int) extends Tree
    
    trait Scaler[T <: Tree] extends ((T, Int) => T)
    
    object Scaler {
      implicit object scalesLeafs extends Scaler[Leaf] {
        def apply(l: Leaf, s: Int) =
          Leaf(l.n * s)
      }
    
      implicit def scalesNodes[L <: Tree: Scaler, R <: Tree: Scaler] = new Scaler[Node[L,R]] {
        val ls = implicitly[Scaler[L]]
        val rs = implicitly[Scaler[R]]
    
        def apply(n: Node[L,R], s: Int) =
          Node(ls(n.l, s), rs(n.r, s))
      }
    }
    
    object demo extends App {
      def scale[T <: Tree](t: T, s: Int)(implicit ev: Scaler[T]): T =
        ev(t, s)
    
      val check1 = scale(Leaf(3), 5)
      val check2 = scale(Node(Leaf(3), Leaf(7)), 5)
    
      Console println check1.n
      Console println check2.l.n
      Console println check2.r.n
    }
    

    编辑:作为旁注:如果您有一个树不变量,例如所有右侧的叶子都大于或等于左侧的叶子,您可能需要考虑实现 scale就映射树而言,从而有效地创建一棵新树,因为使用负数进行缩放可能会违反不变量。

    【讨论】:

      猜你喜欢
      • 2022-08-03
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      相关资源
      最近更新 更多