Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I separate a list of ADTs into its variants?

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]
like image 911
simpadjo Avatar asked Nov 07 '22 23:11

simpadjo


1 Answers

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.

like image 133
Puneeth Reddy V Avatar answered Nov 14 '22 21:11

Puneeth Reddy V