The list in scala is not updated

I am new to Scala Collections and currently want to separate this list of strings into a tuple of two lists (List[String], List[String]), which contains a list of palindrome strings and the rest of the input strings.

For example, if the input List("racecar", "abcd", "lilil", "effg") output should be(List("racecar", "lilil"), List("abcd", "effg"))

I have a solution using a filter. But we are currently trying to refine my solution with foldLeft. My new approach is as follows:

def stringTuples2(strings: List[String]): (List[String], List[String]) = {
strings.foldLeft((List[String](), List[String]()))((b, a) => {
  if (a.equals(a.reverse)) { b._1 :+ a; b }
  else { b._2 :+ a; b }
})}

I'm not sure what I'm doing wrong, but the output for this solution is a Tuple of two empty lists, i.e. (List (), List ()).

Help is appreciated. Thank!

+4
source share
1 answer

b List, List b, . ;b : (b._1 :+ a, b._2) (b._1, b._2 :+ a)

, .

List("racecar", "abcd", "lilil", "effg").partition(s => s == s.reverse)
+8

Source: https://habr.com/ru/post/1680382/


All Articles