我有一个List,它可能包含比较相等的元素.我想要一个类似的List,但删除了一个元素.所以从(A,B,C,B,D)我希望能够"移除"一个B来得到例如(A,C,B,D).结果中元素的顺序无关紧要.
我有工作代码,在Scala中用Lisp启发的方式编写.有没有比较惯用的方法呢?
上下文是一种纸牌游戏,其中有两副标准牌正在进行中,因此可能存在重复的牌但仍然一次只能打一张牌.
def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
if (Nil == right) {
return left
}
if (c == right.head) {
return left ::: right.tail
}
return removeOne(c, right.head :: left, right.tail)
}
def removeCard(c: Card, cards: List[Card]): List[Card] = {
return removeOne(c, Nil, cards)
}
Run Code Online (Sandbox Code Playgroud) 例如,如果我有一个列表List(1,2,1,3,2),我想只删除一个1,所以我得到了List(2,1,3,2).如果另一个1被删除它会没事的.
我的解决方案是:
scala> val myList = List(1,2,1,3,2)
myList: List[Int] = List(1, 2, 1, 3, 2)
scala> myList.patch(myList.indexOf(1), List(), 1)
res7: List[Int] = List(2, 1, 3, 2)
Run Code Online (Sandbox Code Playgroud)
但我觉得我错过了一个更简单的解决方案,如果是这样,我错过了什么?