У меня была эта функция для функционального обхода графа:
private def dfs(current: RCell, rCellsMovedWithEdges: Vector[RCell], acc: Vector[RCell] = Vector()): Vector[RCell] = {
current.edges.foldLeft(acc) {
(results, next) =>
if (results.contains(rCellsMovedWithEdges(next))) results
else dfs(rCellsMovedWithEdges(next), rCellsMovedWithEdges, results :+ current)
} :+ current
}
Реализация взята из Мануэля Кисслинга здесь
Это довольно мило, но я волнуюсь, что ": current" в конце делает его не хвостовым рекурсивом.
Я изменил это на:
private def dfs(current: RCell, rCellsMovedWithEdges: Vector[RCell]): Vector[RCell] = {
@annotation.tailrec
def go(current: RCell, rCellsMovedWithEdges: Vector[RCell], acc: Vector[RCell] = Vector()): Vector[RCell] = {
current.edges.foldLeft(acc) {
(results, next) =>
if (results.contains(rCellsMovedWithEdges(next))) results
else go(rCellsMovedWithEdges(next), rCellsMovedWithEdges, results :+ current)
}
}
go(current, rCellsMovedWithEdges) :+ current
}
но компилятор говорит, что рекурсивный вызов не находится в хвостовой позиции.
Есть ли у левого хвоста рекурсивный хвост за шанс?
Если нет, есть ли другой способ сделать то, что я хочу?