这次行动的好名字是什么?

Rog*_*ach 2 scala

我看到Scala标准库错过了获取集合中对象范围的方法,它满足谓词:

def <???>(p: A => Boolean): List[List[A]] = {
  val buf = collection.mutable.ListBuffer[List[A]]()
  var elems = this.dropWhile(e => !p(e))
  while (elems.nonEmpty) {
    buf += elems.takeWhile(p)
    elems = elems.dropWhile(e => !p(e))
  }
  buf.toList
}
Run Code Online (Sandbox Code Playgroud)

这种方法有什么好名字?我的实施是否足够好?

oxb*_*kes 7

我会选择chunkWithchunkBy

至于你的实现,我认为这需要递归!看看你是否可以填写这个

@tailrec def chunkBy[A](l: List[A], acc: List[List[A]] = Nil)(p: A => Boolean): List[List[A]] = l match {
  case Nil => acc
  case l    =>
    val next = l dropWhile !p
    val (chunk, rest) = next span p
    chunkBy(rest, chunk :: acc)(p)
}
Run Code Online (Sandbox Code Playgroud)

为什么递归?理解算法要容易得多,而且更容易没有bug(假设没有变量).

用于否定谓词的语法!p是通过隐式转换实现的

implicit def PredicateW[A](p: A => Boolean) = new {
  def unary_! : A => Boolean = a => !p(a)
}
Run Code Online (Sandbox Code Playgroud)

我通常会保留它,因为它非常有用