我有一个列表,其中可能包含比较相等的元素。我想要一个类似的列表,但删除了一个元素。因此,从 (A, B, C, B, D) 中,我希望能够仅“删除”一个 B 以获得例如(甲、丙、乙、丁)。结果中元素的顺序并不重要。
我有工作代码,是用 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)
}
最佳答案
我在上面的答案中没有看到这种可能性,所以:
scala> def remove(num: Int, list: List[Int]) = list diff List(num)
remove: (num: Int,list: List[Int])List[Int]
scala> remove(2,List(1,2,3,4,5))
res2: List[Int] = List(1, 3, 4, 5)
编辑:
scala> remove(2,List(2,2,2))
res0: List[Int] = List(2, 2)
就像一个魅力:-)。
关于list - 从不可变列表中获取 "remove"一个元素的惯用 Scala 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5636717/