我有一些这样的代码,带有嵌套的迭代器。如果 find 返回和 Some(value),我想停止,退出 foreach/map 和 return(value),并继续 incase 的 None。这里的正确方法是什么?
编辑:这是完整的功能
Line Schema: line_id, name
Stop Schema: stop_id, x, y
Time Schema: line_id, stop_id, time
Run Code Online (Sandbox Code Playgroud)
给定时间和 x,y 我想找到 line_id 和 name。所以暂时我坚持获取 valueWhichImTryingToGet。
def findVehicle(time: String, x: String, y: String) = {
val stopIter = Source.fromFile("stops.csv").getLines().drop(1)
val stopCols = stopIter.map(_.split(",").map(_.trim))
val stopIds = stopCols.filter(arr => arr(1) == x && arr(2) == y)
val valueWhichImTryingToGet = stopIds.map { arr =>
val iter = Source.fromFile("times.csv").getLines().drop(1)
val cols = iter.map(_.split(",").map(_.trim))
cols.find(col => col(1) == arr(0) && col(2) == time) match {
case Some(value) => value(0) //String type
case None => NotFound(s"No Vehicle available at the given time ${time}")
}
}
val lineIter = Source.fromFile("lines.csv").getLines().drop(1)
val lineCols = lineIter.map(_.split(",").map(_.trim))
lineCols.find(_(0) == valueWhichImTryingToGet ).getOrElse("No vechile can be found with the given information")
}
Run Code Online (Sandbox Code Playgroud)
还有代码方面的改进吗?
我注意到的另一件事是,如果我对迭代器stopIds进行长度/大小检查,它会耗尽迭代器,并且不会发生进一步的处理。那么我怎样才能找到第一个过滤器是否返回 0?
您的逻辑可以像这样或多或少地不间断地表达(我没有深入研究领域上下文,因为它显然无关紧要,您可以自己调整):
// instead of running whole code for all entries we can just check
// if value exist within some set of values
val stopIds = cols.filter(arr=> arr(1) == x && arr(2) == y).map(_(0)).toSet
Source
.fromFile("abc.csv")
.getLines()
.drop(1) // drop headers
.map { line =>
line.split(",").map(_.trim).toList
}
.collectFirst {
// find first entry which has second value from stopIds set
// and third value equal to expected time
case _ :: id :: atTime :: _ if stopIds.contains(id) && atTime == time =>
Vehicle(value(0), value(1))
}
.getOrElse {
// if no matching value is found fall back on "not found" case
NotFound(s"No Vehicle available at the given time ${time}")
}
Run Code Online (Sandbox Code Playgroud)
作为旁注 - 我会在这里推荐一些合适的 CSV 库,因为这个解决方案不是防弹的,如果有人创建了一个带有转义昏迷的文件,它就会中断。
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |