如何将ADT列表分为不同的变体

如何将ADT列表分为不同的变体

是否可能以某种方式将解决方案扩展到求和类型?

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]

最佳答案

也许您可以尝试改善此答案。这可能无法解决您的问题,因为很难知道给定类型的任意子类型(Group类型可能具有任意数量的子类型)。对于Either,很容易预测其子类型为RightLeft

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)))

希望这对您有所帮助。

关于scala - 如何将ADT列表分为不同的变体?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53524410/

10-10 04:18