使用Scala中的Free Monads Trampoline进行递归函数堆栈安全吗?

时间:2017-07-17 17:01:19

标签: scala recursion scalaz scala-cats

我为我的模特指定了特征:

sealed trait TreeStructureModel{
  val parentId: Option[Long]
  val title: String
  val id: Long
}

然后我从DB的记录中构建一棵树:

trait SimpleTree[+TreeStructureModel]{
  val title: String
  val id: Long
}
trait Node[+TreeStructureModel] extends SimpleTree[TreeStructureModel]{
  val inner: List[SimpleTree[TreeStructureModel]]
}
trait Leaf[+TreeStructureModel] extends SimpleTree[TreeStructureModel]

case class NodeImp[T <: TreeStructureModel](title: String, inner: List[SimpleTree[T]], id: Long) extends Node[T]
case class LeafImp[T <: TreeStructureModel](title: String, id: Long) extends Leaf[T]

object SimpleTree{
  def apply[T <: TreeStructureModel](ls: List[T]): List[SimpleTree[T]] = {
    def build(ls: List[T], current: T): SimpleTree[T] = {
      val children = ls.filter{ v => v.parentId.isDefined && v.parentId.get == current.id}
      if(children.isEmpty){
        LeafImp(title = current.title, id = current.id)
      } else {
        val newLs = ls.filterNot{ v => v.parentId.isDefined && v.parentId.get == current.id}
        NodeImp(title = current.title, id = current.id, inner = children.map{ch => build(newLs, ch)})
    }
  }
    val roots = ls.filter{ v => v.parentId.isEmpty}
    val others = ls.filterNot{ v => v.parentId.isEmpty}
    roots.map(build(others, _))
  }
}

此代码工作正常,但使用非尾递归调用。所以,我担心的是它会在大量记录中失败。我找到了一个很好的article使用Free monads Trampoline进行非尾递归。 这看起来像是一种方法,但我不能重写我的代码,使其堆栈安全。在文章的例子中,函数中只有一个递归调用,但在我的函数中可以有很多,用于构建树。有人对Free monads更有经验可以帮助我吗?这甚至可能吗?

2 个答案:

答案 0 :(得分:1)

您可以将函数重写为tail-recursive,而不使用scalaz。奥卡姆剃刀,你知道......

 def build(
   ls: List[T], 
   kids: Map[Long, List[T]],
   result: Map[Long, SimpleTree[T]]
 ) = ls match {
   case Nil => result
   case head :: tail if result.contains(head.id) => build(tail, kids, result)
   case head :: tail =>          
     kids(head.id).partition(result.contains(_.id)) match {
       case (Nil, Nil) => 
         build(tail, kids, result + (head.id->LeafImp(head.title, head.id)))
       case (done, Nil) => 
         build(
           tail,
           kids, 
           result + 
           (head.id->NodeImp(head.title, head.id, done.map(_.id).map(result)))
         )
       case (_, missing) =>
         build(missing ++ tail, kids, result)
     }
  }

  def apply(ls: List[T]) = {
    val (roots, others) = list.partition(_.parentId.isEmpty)
    val nodes = build(ls, others.groupBy(_.parentId.get), Map.empty)
    roots.map(_.id).map(nodes)
  }

答案 1 :(得分:1)

阐述我的评论,使build方法返回Trampoline并使用traverse代替map

import scalaz.Free.Trampoline
import scalaz.Trampoline
import scalaz.syntax.traverse._
import scalaz.std.list._

sealed trait TreeStructureModel{
  val parentId: Option[Long]
  val title: String
  val id: Long
}

trait SimpleTree[+TreeStructureModel]{
  val title: String
  val id: Long
}
trait Node[+TreeStructureModel] extends SimpleTree[TreeStructureModel]{
  val inner: List[SimpleTree[TreeStructureModel]]
}
trait Leaf[+TreeStructureModel] extends SimpleTree[TreeStructureModel]

case class NodeImp[T <: TreeStructureModel](title: String, inner: List[SimpleTree[T]], id: Long) extends Node[T]
case class LeafImp[T <: TreeStructureModel](title: String, id: Long) extends Leaf[T]

object SimpleTree{
  def apply[T <: TreeStructureModel](ls: List[T]): List[SimpleTree[T]] = {
    def build(ls: List[T], current: T): Trampoline[SimpleTree[T]] = {
      val children = ls.filter{ v => v.parentId.isDefined && v.parentId.get == current.id}
      if(children.isEmpty){
        Trampoline.done(LeafImp(title = current.title, id = current.id))
      } else {
        val newLs = ls.filterNot{ v => v.parentId.isDefined && v.parentId.get == current.id}
        children.traverse(build(newLs, _)).map(trees => NodeImp(title = current.title, id = current.id, inner = trees))
      }
    }
    val roots = ls.filter{ v => v.parentId.isEmpty}
    val others = ls.filterNot{ v => v.parentId.isEmpty}
    roots.map(build(others, _).run)
  }
}

请注意,我对您的代码进行了最少的必要更改以使用Trampoline。我还建议您使用partition一次,而不是一对filterfilterNot

使方法直接递归是一个很好的练习。