I'm in the process of learning Scala and am trying to write some sort of function that will compare one element in an list against an element in another list at the same index. I know that there has to be a more Scalatic way to do this than two write two for
loops and keep track of the current index
of each manually.
Let's say that we're comparing URLs, for example. Say that we have the following two List
s that are URLs split by the /
character:
val incommingUrl = List("users", "profile", "12345")
and
val urlToCompare = List("users", "profile", ":id")
Say that I want to treat any element that begins with the :
character as a match, but any element that does not begin with a :
will not be a match.
What is the best and most Scalatic way to go about doing this comparison?
Coming from a OOP background, I would immediately jump to a for
loop, but I know that there has to be a good FP way to go about it that will teach me a thing or two about Scala.
EDIT
For completion, I found this outdated question shortly after posting mine that relates to the problem.
EDIT 2 The implementation that I chose for this specific use case:
def doRoutesMatch(incommingURL: List[String], urlToCompare: List[String]): Boolean = {
// if the lengths don't match, return immediately
if (incommingURL.length != urlToCompare.length) return false
// merge the lists into a tuple
urlToCompare.zip(incommingURL)
// 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
}
You can use zip
, that invoked on Seq[A]
with Seq[B]
results in Seq[(A, B)]
. In other words it creates a sequence with tuples with elements of both sequences:
incommingUrl.zip(urlToCompare).map { case(incomming, pattern) => f(incomming, pattern) }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments