我刚刚有一个用例,我需要将一个列表拆分为 n 个子列表,以便从原始列表中按顺序获取元素并分组,而子列表的谓词为真(当它为假时,启动一个新的子列表) . 我在标准库中没有找到这个功能,我认为尝试以功能样式解决它是一个很好的练习(因为我离功能大师还很远)。
下面是我想出的代码。但我怀疑它可以改进很多。你能帮我找到更好的编码方法吗?
class ListWithSplitter[A](val theList:List[A])
{
private def sublistWhile(list:List[A], pred:(List[A] => Boolean)):(List[A],List[A]) =
{
def combine(okList:List[A], remaining:List[A], pred:(List[A] => Boolean)):(List[A],List[A]) =
{
if(pred(okList ::: remaining.head :: Nil))
combine(okList ::: remaining.head :: Nil, remaining.tail, pred)
else
(okList, remaining)
}
list match {
case Nil => (Nil, Nil)
case x :: Nil => (list, Nil)
case x :: xs => combine(List(x), xs, pred)
}
}
private def combinedSplit(list:List[A], pred:(List[A] => Boolean)):List[List[A]] =
{
val r = sublistWhile(list, pred)
r match {
case (Nil, Nil) => List(Nil)
case (x, Nil) => List(x)
case (x, y) => x :: combinedSplit(y, pred)
}
}
def combinedSplit(pred:(List[A] => Boolean)):List[List[A]] =
{
combinedSplit(theList, pred)
}
}
trait ListCombinedSplit
{
implicit def list2combSplitter[A](x:List[A]) : ListWithSplitter[A] = new ListWithSplitter(x)
}
object ListSplitter extends ListCombinedSplit {
def main(args:Array[String])
{
// sample usage: sum of each sublist is less than 100
val a = List(4, 59, 10, 24, 42, 9, 2, 44, 44, 44, 44)
val b = a combinedSplit { list:List[Int] => ((0 /: list)(_ + _)) < 100 }
b foreach println
}
}
样品的结果是:
List(4, 59, 10, 24)
List(42, 9, 2, 44)
List(44, 44)
List(44)