Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Lists of Strings in Scala

Tags:

string

list

scala

I know lists are immutable but I'm still confused on how I would go about this. I have two lists of strings - For example:

var list1: List[String] = List("M", "XW1", "HJ", "K")
var list2: List[String] = List("M", "XW4", "K", "YN")

I want to loop through these lists and see if the elements match. If it doesn't, the program would immediately return false. If it is a match, it will continue to iterate until it finds an element that begins with X. If it is indeed an X, I want to return true regardless of whether the number is the same or not.

Problem I'm having is that currently I have a conditional stating that if the two elements do not match, return false immediately. This is a problem because obviously XW1 and XW4 are not the same and it will return false. How can I bypass this and determine that it is a match to my eyes regardless of the number?

I also have a counter a two length variables to account for the fact the lists may be of differing length. My counter goes up to the shortest list: for (x <- 0 to (c-1)) (c being the counter).


2 Answers

You want to use zipAll & forall.

def compareLists(l1: List[String], l2: List[String]): Boolean =
  l1.zipAll(l2, "", "").forall {
    case (x, y) =>
      (x == y) || (x.startsWith("X") && y.startsWith("X"))
  }

Note that I am assuming an empty string will always be different than any other element.

like image 150
Luis Miguel Mejía Suárez Avatar answered Dec 08 '25 23:12

Luis Miguel Mejía Suárez


If I understand your requirement correctly, to be considered a match, 1) each element in the same position of the two lists being simultaneously iterated must be the same except when both start with X (in which case it should return true without comparing any further), and 2) both lists must be of the same size.

If that's correct, I would recommend using a simple recursive function like below:

def compareLists(ls1: List[String], ls2: List[String]): Boolean = (ls1, ls2) match {
  case (Nil, Nil) =>
    true
  case (h1 :: t1, h2 :: t2) =>
    if (h1.startsWith("X") && h2.startsWith("X"))
      true  // short-circuiting
    else
      if (h1 != h2)
        false
      else
        compareLists(t1, t2)
  case _ =>
    false
}
like image 20
Leo C Avatar answered Dec 08 '25 22:12

Leo C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!