如何在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]
当然,我可以用几种不同的方法自己实现这个方法,但是没有一种方法显然是最好的。我不想将我的列表转换为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)
}
然而,使用链表索引通常不是最高效的方式。
我可以编写一个更高效的方法,如下所示:
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)
}
然而,那并不十分简洁。看起来很奇怪为什么没有现有的方法可以让我高效且简洁地完成此操作。那么,我是否遗漏了什么,或者我的最终方案确实是最好的?