Search code examples
scalazipunpack

scala unpack tuple into case class arguments and additional zip two sequences


I want to transform Seq[String, Seq[Char]] into Seq[UnpackedObject] but don't know how to unpack tuple of two Chars (A, B) to separate case class arguments.

I want to basically create s3 out of s1 and s2 such that:

Seq(("aaa", "A", B"), ("bbb", "B", C"), ("ccc", "C", "D"), ("ddd", "D", "D"))

hence I am trying to use case class but:

  • problem 1: unpacking tuple into two arguments;
  • problem 2: last element with "D", "D" <-- I don't know how to solve it.
val s1 = Seq("aaa", "bbb", "ccc", "ddd")
val s2 = ('A' to 'D').sliding(2).toSeq
val pairs = (s1, s2).zipped.map { case (a, b) => UnpackedObject(a, b) }
    
case class UnpackedObject(a: String, b: Char, c: Char)

this above is my code so far.


Solution

  • zipped function expects Seq with the same length but you passed s2 of length 3 and s1 length is 4. You need to add one element into s2 to get s3:

    val s1 = Seq("aaa", "bbb", "ccc", "ddd") 
    val s2 = ('A' to 'D').sliding(2).toSeq :+ Seq('D', 'D')
    // ('A' to 'D').sliding(2) will return just 
    // Seq(Seq('A', 'B'), Seq('B', 'C'), Seq('C', 'D'))
    val pairs = (s1, s2).zipped.map { case (a, b) => (a, b.head, b.last) }
    // will return Seq((aaa,A,B), (bbb,B,C), (ccc,C,D), (ddd,D,D))
    

    if you need to create UnpackedObject, you can do it just call tupled apply function of case class:

    val objects = (s1, s2).zipped.map { case (a, b) => (a, b.head, b.last) }
      .map((UnpackedObject.apply _).tupled)
    // will return 
    // Seq(
    //   UnpackedObject(aaa,A,B), UnpackedObject(bbb,B,C), 
    //   UnpackedObject(ccc,C,D), UnpackedObject(ddd,D,D))