2

I have a List with various types like so:

val data: List[(String, Int, List[String])] = List(("foo", 1, List("a", "b")), ("bar", 2, List("c", "d")), ("baz", 1, List("e", "f")))

Where there is an Int value large than 1, I am trying to replicate those items for each Int in that range (from 1 to Int) - so ideally it would look like (emphasizing that the Int needs to be incremented for each iteration from 1 to Int):

val dataExpanded: List[(String, Int, List[String])] = List(("foo", 1, List("a", "b")), ("bar", 1, List("c", "d")), ("bar", 2, List("c", "d")), ("baz", 1, List("e", "f")))

Working with types in scala routinely does my head in, particularly with nested strucutures since every operation seems to introduce more and more type pitfalls.

So while I am trying:

val dataExpanded = data.map{ case (s, i, l) =>

    if (i > 1) {

        List.range(1, i+1).map { n =>
            (s, n, l)
        }

    } else {
        (s, i, l)
    }
} 

I get the result:

> dataExpanded: List[Product with java.io.Serializable] = List((foo,1,List(a, b)), List((bar,1,List(c, d)), (bar,2,List(c, d))), (baz,1,List(e, f)))

The result looks like it is on the right path, but the expanded elements are nested in their own list and, as a result, I think, the Type is wrong. no amount of flatMapping or flattening or mapping the output of the for loop is getting me out of this jam.

This might also have to do with my case statement and not handling a None case, but I am not sure how to handle the other cases (I know it's not right to say, but I won't really have any other cases in my data - though that's the inebriation of dynamically typed languages talking)

Is there a way to maintain the expected types when going from data to dataExpanded while avoiding needless loops?

1
  • The problem is that the types are different in the two branches of the if/else (with stricter compiler arguments this would be an error, which might have helped you find the problem). You could make the else branch List((s, i, l)) and then you'd just have to flatten. Though as you can see from the suggestions, you don't really need the if/else at all - the code in the if branch works fine even when i=1.
    – lmm
    Jan 13, 2015 at 22:20

3 Answers 3

6

Consider case classes for the tuples, like this

case class Datum(s: String, n: Int, xs: List[String])

and thus given

val data: List[Datum] = List(Datum("foo", 1, List("a", "b")), 
                             Datum("bar", 2, List("c", "d")), 
                             Datum("baz", 1, List("e", "f")))

we can use the copy method in case classes as follows,

def expand(d: Datum) = (1 to d.n).map (i => d.copy(n=i))

which copies the fields contents and modifies specified fields, in this case n. Hence for data,

data.flatMap(expand(_))

delivers the desired output.

1

You were close, you could have done

val dataExpanded = data.flatMap {
case (s, i, l) =>
  List.range(1, i + 1).map { n =>
    (s, n, l)
  }
 }                                               

//> dataExpanded  : List[(String, Int, List[String])] = List((foo,1,List(a, b)),
                        (bar,1,List(c, d)), (bar,2,List(c, d)), (baz,1,List(e, f)))

Or more neatly as

val dataExpanded = data.flatMap {
    case (s, i, l) =>
      (1 to i).map ((s, _, l))
  }                                              
0

A little more verbose than @enzyme answer but here is an approach with recursion, pattern matching, and a for expression to generate the List of tuples.

def expand(xs: List[Tuple3[String, Int, List[String]]]): List[Tuple3[String,Int, List[String]]] = xs match {
 case Nil => Nil
 case h :: t => if (h._2 == 1) 
                  h :: expand(t)
                else
                  (for(i <- 1 to h._2) yield (h._1, i, h._3)).toList ++ expand(t)
}

Outputs:

scala> expand(data)
List[(String, Int, List[String])] = List((foo,1,List(a, b)), (bar,1,List(c, d)), (bar,2,List(c, d)), (baz,1,List(e, f)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.