2

我有一个递归的方法。scala中是否有办法根据缓冲区的大小进行突破(如下所示)?例如,当 elementList.size > 5 时爆发的情况?

val elementList = ListBuffer.empty[Book]
@tailrec
def getBooks(elements: List[Element]) {
  elements match {
    case Nil => info("Reached end of elements list.")
    case element :: rest if element.getElementType == ElementType.BOOK => {
      elementList.append(element.getBook) 
      getLooks(rest)
    }
    case _ => getBooks(elements.tail)
  }
}
4

2 回答 2

1

I guess the most simple way would be to just wrap an if statement around your match statement like this:

val elementList = ListBuffer.empty[Book]
@tailrec
def getBooks(elements: List[Element]) {
  if (elementList.size <= 5){
    elements match {
      case Nil => info("Reached end of elements list.")
      case element :: rest if element.getElementType == ElementType.BOOK => {
        elementList.append(element.getBook) 
        getLooks(rest)
      }
      case _ => getBooks(elements.tail)
    }
  }
}
于 2013-06-07T11:52:12.237 回答
0

一般来说,您可以尝试在递归中传递剩余元素的数量。

例如:

  def get(list: List[Int], max: Int): List[Int] = {

    @tailrec
    def get(list: List[Int], acc: List[Int], remaining: Int): List[Int] = {
      list match {

        case h :: tail if remaining > 0 =>
          get(tail, h :: acc, remaining - 1)

        case _ =>
          acc
      }
    }

    // Requires reverse() !
    get(list, Nil, max).reverse

至于累加器:您可以改用缓冲区,以防止reverse()最后出现。

于 2013-06-07T12:35:47.363 回答