Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List in scala not getting updated

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

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

I have got a solution using filter. But, currently, trying to refine my solution using 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 am not sure, what I am doing wrong, but the output for this solution is Tuple of two empty lists, i.e. (List(), List()).

Help is appreciated. Thanks!

like image 661
PankajK Avatar asked Jan 30 '23 02:01

PankajK


1 Answers

Your attempt to modify b creates a new List, you then throw the new List away and return b, which is unchanged. Take out the ;b part and return the updated tuple: (b._1 :+ a, b._2) or (b._1, b._2 :+ a)

BTW, here's a different approach to the solution.

List("racecar", "abcd", "lilil", "effg").partition(s => s == s.reverse)
like image 101
jwvh Avatar answered Feb 07 '23 20:02

jwvh