Reputation: 393
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
Reputation: 1730
As stated by thefourtheye, your function returns the results of fold
s. 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