简体   繁体   中英

Scala - Vector contains (types comparison)

I'm trying to check in a Vector of "paths" which ones contain all the stops wanted. I already created a function that gives all the paths that have a given stop.

    def pathIncludesPoint(pathList: PathList, stopWanted: Point): Option[Vector[Path]] = {

     if (pathList.paths.isEmpty) None

     else Some(

       for {
         path <- pathList.paths
         stop <- path.stops
         if stop.contains(stopWanted)
       } yield path)

    }

   def pathIncludesListOfPoint(pathList: PathList, stopsWanted: Vector[Point]): Option[Vector[Path]] = {

      if (pathList.paths.isEmpty) None

      else Some(

        pathList.paths.filter(path => stopsWanted.forall(stopWanted => pathIncludesPoint(pathList, stopWanted).contains(path)))

      )

   }

I'm trying to check if the Vector contains the path wanted :

pathList.paths.filter(path => stopsWanted.forall(stopWanted => pathIncludesPoint(pathList, stopWanted).contains(path)))

but the last path return an error because I'm comparing a Vector[Path] (what returns the function "pathIncludesPoint") and a Path. I don't understand using the scala Library my error.

Thanks!

Here is the structure of Path and PathList if needed :

case class Path(segments: Vector[Segment]) {

  def stops: Option[Vector[Point]] = {

    if (segments.isEmpty) None

    else Some({

      for {
        segment <- segments
      } yield segment.from

     }.tail)}

}



case class PathList(paths: Vector[Path]) {

}

在此处输入图片说明

The error occurs because pathIncludesPoint(pathList, stopWanted) has type Option[Vector[Path]] , so your .contains(path) is actually working on the Option , not on the Vector .

To fix this, maybe you can drop some uses of Option and just return an empty Vector where you currently return None ?

Or if you want to keep all uses of Option and just want to fix the line with the .contains , you can use .exists as follows:

pathIncludesPoint(pathList, stopWanted).exists(_.contains(path))

Here, the .exists handles the Option and the .contains handles the Vector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM