Home > OS >  I have a List[(List[A], List[R])] - a List of a tuple of two Lists of objects A and R respectively.
I have a List[(List[A], List[R])] - a List of a tuple of two Lists of objects A and R respectively.

Time:11-19

I have a List[(List[A], List[R])] - a List of a tuple of two Lists of objects A and R respectively.

For example, List[([A1, A2], [R1, R2, R3])]

What I want to do is convert this into a List[(List[A], R)] for every R object. So basically, make a List[Tuple2] where the R object is “flattened” for the list of A objects.

Example - For the above example, the overall List should get divided into 3 sublists looking like:



List[([A1, A2], R1)]
List[([A1, A2], R2)]
List[([A1, A2], R3)]

I need to get every single R element given any list of A elements. The reason for this is that the A elements can contain nested sub-A elements and multiple R elements, so I need to segregate each R as being part of a List[A].

So far, this is what I’ve tried but I have no idea how to do the "flatten" part of my question:


lazy val rules: List[(List[A], R)] = {
    //listOfA = List[A1, A2, A3,…]
    //listOfR = List[R1, R2, R3, …]
    val fromA = listOfA.map { A => (List(A.description)    A.subGroups.map(_.description), A.rules) } // Currently: List[(List[A], List[R])]  Required: List[(List[A], R)]
    val fromR = listOfR.map { r => (Nil, r) } // List[(Nil, R)]
    fromA    fromR
}

This is the definition for the A case class:

case class A(description: Descriptor, rules: List[R], subGroups: List[A])

… and case class R just contains the List[R] directly. In case of the fromR defintion, there is no List[A] present hence that is substituted by Nil to represent blank List[A].

As you can see, for the val fromR I can just get the individual R by map-ing it as I have done in fromR. I need to get a combined result from fromA fromR (as it may be possible that my input contains a mix of R's within A and direct R's). 


My problem is with the fromA definition. So far, I have only been able to get the List[R] for every List[A]. How can I segregate each R for every List[A]… the problem is mainly with the A.rules definition.

Please help as I am new to Scala.

CodePudding user response:

Actually I got lost in the question a bit, after the explanation of the problem, but I'm assuming you want to convert a List[(List[A], List[R])] into a List[(List[A], R)] for each R in the list. A nice and easy way to do this would be to use for comprehensions:

val result: List[(List[A], R)] = for {
    (as, rs) <- firstList
    r <- rs
  } yield (as, r)

You can also use the equivalent approach, but with flatMap, map:

val result: List[(List[A], R)] = firstList.flatMap { case (as, rs) => 
  rs.map {r => 
    (as, r)
  }
}
  • Related