scala递归循环与未来的结果

时间:2017-07-31 08:22:27

标签: scala playframework

我的控制器中有一个功能:

 def getPreviousVersions(id: Int): Action[AnyContent] = Action.async {
    val result: Future[Option[ElementModel]] =  dto.getPreviousVersion(id)

    // while-loop or whatever is best practice
    // val arrayOfElements: Future[Seq[ElementModel] = ...

    val c = for {
      previousVersions <- arrayOfElements
    } yield previousVersions 

    //do something with the versions
    //Return something in the end
  }

我的模型看起来像这样:

case class ElementModel(
                                  ...
                                  previousVersion: Option[Int],
                                  ...)

我将最新的previousVersion的id存储在我的模型中。现在,我想要做的是递归迭代或使用while循环迭代或任何最佳实践迭代来获取previousVersion的previousVersion,依此类推。 我们的想法是获取所有以前的版本,将它们存储在序列中并将此seq传递给另一个函数。

有没有顺利,正确的方法来做到这一点?谢谢!

2 个答案:

答案 0 :(得分:2)

def getVersionSequence(id: Int): Future[List[ElementModel]] = {

  def _getVersionSequence(id: Int, fList: Future[List[ElementModel]]): Future[List[ElementModel]] = {
    dto.getPreviousVersion(id).flatMap({
      case Some(elementModel) => elementModel.previousVersion match {
        case Some(pVId) => _getVersionSequence(pVId, fList.map(list => elementModel +: list))
        case None => fList.map(list => elementModel +: list)
      }
      case None => fList
    })
  }

  val fInvertedList = _getVersionSequence(id, Future(List.empty[ElementModel]))

  fInvertedList.map(list => list.reverse)
}


def getPreviousVersions(id: Int): Action[AnyContent] = Action.async {
  val c: Future[List[ElementModel]] = getVersionSequence(id)

  //do something with the versions
  //Return something in the end
}

答案 1 :(得分:1)

 def getPreviousVersion(previousVersionId: Int): Future[ElementModel] = dto.getElementModelForId(previousVersionId)
/*This has been changed from your question, you shouldn't need a getPreviousVersion(id) function in your database connector, but merely a function to get an element by id*/

 def getAllPreviousVersions(e: ElementModel): Future[Seq[ElementModel]] = {
    e.previousVersion match {
      case None => Future.successful(Seq(e))
      case Some(id) => getPreviousVersion(id).flatMap {
        previousVersionElement =>
          getAllPreviousVersions(previousVersionElement).map {
            //Properly preserves order !
            seq => previousVersionElement +: seq
          }
      }
    }
  }

 def getPreviousVersions(e: ElementModel) = {

    getAllPreviousVersions(e).map {

      //do something with the versions
      //Return something in the end
      ???
    }
  }