Is it possible to somehow extend the solution to a sum type?
sealed trait Group
case class A extends Group
case class B extends Group
case class C extends Group
def divide(l : List[Group]): //Something from what I can extract List[A], List[B] and List[C]
May be you can try improving this answer. This may not solve your problem as it is difficult to know the the arbitrary subtypes of a given type (Group type might have any number of subtypes). In the case of Either it is easy to predict it's subtype as Right or Left.
sealed trait Group
case class A(name:String) extends Group
case class B(name:String) extends Group
case class C(name:String) extends Group
val list = List(
A("a1"), A("a2"), A("a3"), A("a4"),
B("b1"), B("b2"), B("b3"), B("b4"),
C("c1"), C("c2"), C("c3"), C("c4")
)
def divide(
list: List[Group],
aList : List[A],
bList: List[B],
cList: List[C]
): (List[A], List[B], List[C]) = {
list match {
case Nil => (aList, bList, cList)
case head :: tail => head match {
case a : A => divide(tail, aList.:+(a), bList, cList)
case b : B => divide(tail,aList, bList.:+(b), cList)
case c : C => divide(tail, aList, bList, cList.:+(c))
}
}
}
divide(list, List.empty[A], List.empty[B], List.empty[C])
//res1: (List[A], List[B], List[C]) = (List(A(a1), A(a2), A(a3), A(a4)),List(B(b1), B(b2), B(b3), B(b4)),List(C(c1), C(c2), C(c3), C(c4)))
Hope this helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With