Scala - Check If object exist inside a list -
i'm trying write algorithm check if object exists inside list.
my case class following:
case class person(id:int, name:string, friends:list[person] = nil)
i've wrote using code:
@tailrec final def find(id: int, tree: list[person]):option[person] = tree match { case nil => none case (h :: t) => if(h.id == id) option(h) else find(key, t ::: h.friends) }
is approach? use tail recursive , append list on tail list? if not, best approach?
i ended following implementation tail recursive bfs:
@tailrec def find(id: int, level: list[person], visited: set[person] = set.empty): option[person] = if (level.isempty) none else { // try find person on level val found = level.find(_.id == id).filternot(visited.contains) if (found.isdefined) found else find( id, // next level construction level.flatmap(_.friends).distinct, // keep track of visited handle cycles visited ++ level ) }
update: also, suggest add call name able play around more test cases:
class person(val id: int, val name: string, friends: => list[person]) { def friendlist = friends override def tostring = name } object person { def apply(id: int, name: string, friends: => list[person] = nil) = new person(id, name, friends) }
in case can compose example comments:
val john = person(1, "john") val russ = person(2, "russ") val bob = person(3, "bob") val lois = person(5, "lois") lazy val `eve friends` = list(john, anne) lazy val `peter friends` = list(eve, bob, russ) lazy val `anne friends` = list(peter, lois) val eve = person(7, "eve", `eve friends`) val peter = person(8, "peter", `peter friends`) val anne: person = person(6, "anne", `anne friends`) println(find(8, list(eve, peter, lois))) // result: some(peter)
Comments
Post a Comment