从Scala中的列表中删除第一个对象的最佳方法是什么?
来自Java,我习惯于使用一种List.remove(Object o)方法从列表中删除第一次出现的元素.既然我在Scala中工作,我希望该方法返回一个新的不可变List而不是改变一个给定的列表.我也可能期望该remove()方法采用谓词而不是对象.总之,我希望找到这样的方法:
/**
* Removes the first element of the given list that matches the given
* predicate, if any. To remove a specific object <code>x</code> from
* the list, use <code>(_ == x)</code> as the predicate.
*
* @param toRemove
* a predicate indicating which element to remove
* @return a new list with the selected object removed, or the same
* list if no objects satisfy the given predicate
*/
def removeFirst(toRemove: E => Boolean): List[E]
Run Code Online (Sandbox Code Playgroud)
当然,我可以通过几种不同的方式实现这种方法,但是没有一种方法能够突然出现,因为它显然是最好的.我宁愿不将我的列表转换为Java列表(甚至转换为Scala可变列表)并再次返回,尽管这肯定会有效.我可以用List.indexWhere(p: (A) ? Boolean):
def removeFirst[E](list: List[E], toRemove: (E) => Boolean): List[E] = {
val i = list.indexWhere(toRemove)
if (i == -1)
list
else
list.slice(0, i) ++ list.slice(i+1, list.size)
}
Run Code Online (Sandbox Code Playgroud)
但是,使用带有链表的索引通常不是最有效的方法.
我可以写一个更有效的方法,如下所示:
def removeFirst[T](list: List[T], toRemove: (T) => Boolean): List[T] = {
def search(toProcess: List[T], processed: List[T]): List[T] =
toProcess match {
case Nil => list
case head :: tail =>
if (toRemove(head))
processed.reverse ++ tail
else
search(tail, head :: processed)
}
search(list, Nil)
}
Run Code Online (Sandbox Code Playgroud)
不过,这并不完全简洁.奇怪的是,没有一种现有的方法可以让我有效而简洁地完成这项工作.所以,我错过了什么,或者我的最后一个解决方案真的很好吗?
ret*_*nym 14
您可以稍微清理代码span.
scala> def removeFirst[T](list: List[T])(pred: (T) => Boolean): List[T] = {
| val (before, atAndAfter) = list span (x => !pred(x))
| before ::: atAndAfter.drop(1)
| }
removeFirst: [T](list: List[T])(pred: T => Boolean)List[T]
scala> removeFirst(List(1, 2, 3, 4, 3, 4)) { _ == 3 }
res1: List[Int] = List(1, 2, 4, 3, 4)
Run Code Online (Sandbox Code Playgroud)
在Scala集合API概述是了解一些鲜为人知的方法,一个伟大的地方.