Skip to content

Instantly share code, notes, and snippets.

@iamthiago
Created August 4, 2015 12:13
Show Gist options
  • Select an option

  • Save iamthiago/0bc505a79b08b6dec03d to your computer and use it in GitHub Desktop.

Select an option

Save iamthiago/0bc505a79b08b6dec03d to your computer and use it in GitHub Desktop.
import java.util.UUID
import scala.annotation.tailrec
/**
* Created by Thiago Pereira on 8/4/15.
*/
case class Employee(id: UUID, name: String, parent: Option[Employee])
object TailRecTest {
def main(args: Array[String]) {
val president = Employee(UUID.randomUUID(), "PRESIDENT", None)
val director = Employee(UUID.randomUUID(), "DIRECTOR", Some(president))
val manager = Employee(UUID.randomUUID(), "MANAGER", Some(director))
val employee = Employee(UUID.randomUUID(), "EMPLOYEE", Some(manager))
getParents(employee).foreach(println)
}
def getParents(employee: Employee): List[Employee] = {
@tailrec
def recursion(employee: Employee, employees: List[Employee]): List[Employee] = {
employee.parent match {
case None => employees
case Some(parent) =>
recursion(parent, parent :: employees)
}
}
recursion(employee, Nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment