Scala - 向量包含(类型比较)

Scala - Vector contains (types comparison)

我正在尝试检查 "paths" 的矢量,其中包含所有需要的停靠点。我已经创建了一个函数,它给出了所有具有给定站点的路径。

    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)))

      )

   }

我正在尝试检查 Vector 是否包含所需路径:

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

但是最后一条路径 return 是一个错误,因为我正在比较 Vector[Path](return 函数 "pathIncludesPoint")和路径。我不明白使用 scala 库是我的错误。

谢谢!

如果需要,这里是 Path 和 PathList 的结构:

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]) {

}

错误发生是因为 pathIncludesPoint(pathList, stopWanted) 的类型为 Option[Vector[Path]],因此您的 .contains(path) 实际上是在 Option 上工作,而不是在 Vector 上工作。

要解决此问题,也许您可​​以放弃对 Option 的一些使用,只 return 空 Vector 当前 return None

或者,如果您想保留 Option 的所有用途,而只想用 .contains 修复行,您可以使用 .exists,如下所示:

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

此处,.exists 处理 Option.contains 处理 Vector