【发布时间】:2020-08-13 00:10:02
【问题描述】:
我正在学习 Scala,并且正在尝试编写某种函数,将列表中的一个元素与另一个列表中的元素进行比较在同一索引处。我知道必须有一种比两个编写两个 for 循环并手动跟踪每个循环的当前 index 更可伸缩的方式来做到这一点。
例如,假设我们正在比较 URL。假设我们有以下两个Lists,它们是由/ 字符分割的URL:
val incomingUrl = List("users", "profile", "12345")
和
val urlToCompare = List("users", "profile", ":id")
假设我想将任何以: 字符开头的元素视为匹配项,但任何不以: 开头的元素都不会成为匹配项。
进行这种比较的最佳和最Scalatic的方法是什么?
来自 OOP 背景,我会立即跳到 for 循环,但我知道必须有一个好的 FP 方法来处理它,这将教会我关于 Scala 的一两件事。
编辑
为了完成,我在发布与该问题相关的我的帖子后不久找到了this outdated question。
编辑 2
我为这个特定用例选择的实现:
def doRoutesMatch(incomingURL: List[String], urlToCompare: List[String]): Boolean = {
// if the lengths don't match, return immediately
if (incomingURL.length != urlToCompare.length) return false
// merge the lists into a tuple
urlToCompare.zip(incomingURL)
// iterate over it
.foreach {
// get each path
case (existingPath, pathToCompare) =>
if (
// check if this is some value supplied to the url, such as `:id`
existingPath(0) != ':' &&
// if this isn't a placeholder for a value that the route needs, then check if the strings are equal
p2 != p1
)
// if neither matches, it doesn't match the existing route
return false
}
// return true if a `false` didn't get returned in the above foreach loop
true
}
【问题讨论】:
-
嗨,我只是想让你知道你的实现是有效的,但我更愿意使用 forall 而不是 foreach 来编写检查。这将是一种更 Scala 的方式,无需使用显式的 return 语句。此外,您必须小心,因为如果字符串是空字符串,调用 existingPath(0) 可能会引发异常。 Scala 处理异常的方式是使用 Try monad。
标签: scala functional-programming scala-collections