4

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!

Ramesh Maharjan
  • 41,071
  • 6
  • 69
  • 97
PankajK
  • 187
  • 3
  • 14

1 Answers1

8

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)
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Thanks, @jwvh ! Your explanation really helped me to understand the problem. Also, I understand that `partition()` will really make my life easier in such use cases, it's just that I am trying to learn the different functions and their (possible) caveats. Thanks again! – PankajK Jun 29 '17 at 05:32
  • The best way to thank someone on stack overflow is to accept their answer if it's the best response you have got, and it solves your question. – Ryan Leach Jun 29 '17 at 06:04
  • 1
    @RyanTheLeach , got it! I realize, it's a good learning of Stack Overflow protocols, in addition to Scala! :) – PankajK Jun 30 '17 at 05:22