Eli Golin
Eli Golin

Reputation: 393

Why the following function is not tail recursive?

The following function seems to me as tail recursive
But the compiler still complains if I put a @tailrec above it:

def loop(newInterests: Set[Interest], oldInterests: Set[Interest]): Set[Interest] = {
  newInterests.headOption.fold(oldInterests){ ni =>
    val withSameKeyWord = oldInterests.find(oi => oi.keyword == ni.keyword)

    withSameKeyWord.fold(loop(newInterests.tail, oldInterests + ni)){ k => 
      loop(newInterests.tail,
      oldInterests - k + k.copy(count = k.count + 1))
    }
  }
}

Upvotes: 2

Views: 87

Answers (1)

irundaia
irundaia

Reputation: 1730

As stated by thefourtheye, your function returns the results of folds. A tail recursive version (with pattern matching) would look something like:

@tailrec
def loop(newInterests: Set[Interest], oldInterests: Set[Interest]): Set[Interest] = {
  newInterests.headOption match {
    case None => oldInterests
    case Some(ni) =>
      oldInterests.find(oi => oi.keyword == ni.keyword) match {
        case None => loop(newInterests.tail, oldInterests + ni)
        case Some(k) => loop(newInterests.tail, oldInterests - k + k.copy(count = k.count + 1))
      }
  }
}

Upvotes: 7

Related Questions