Scala:从列表中删除键/值对

时间:2013-09-24 23:57:32

标签: list scala key keyvaluepair

同样,我坚持使用Scala和键/值对的想法。同样,我想以某种方式使用Option。这一次,我坚持如何基于其密钥删除一对,并且只关注该密钥的第一个实例(不是全部)。我试图使用filterfilterNot,但会删除共享相同密钥的所有对。此外,再次尝试使用List实现此功能,以保持半简单

3 个答案:

答案 0 :(得分:0)

很难说出你在问什么。如果你写出了你想写的函数的签名,那将会有所帮助。

也许是这样的事情?

def remove[A, B](seq: Seq[(A, B)], key: A): Seq[(A, B)] = 
  seq.indexWhere(_._1 == key) match { 
    case -1 => seq
    case n => seq.patch(n, Nil, 1)
  }

remove(Seq((1,2), (2,3), (3,4), (2,5)), 2)
// List((1,2), (3,4), (2,5))

remove(Seq((1,2), (2,3), (3,4), (2,5)), 6)
// List((1,2), (2,3), (3,4), (2,5))

答案 1 :(得分:0)

Seq has a method called find完全符合您的要求:

def find(p: (A) ⇒ Boolean): Option[A]

Finds the first element of the sequence satisfying a predicate, if any.

Note: may not terminate for infinite-sized collections.

    p           the predicate used to test elements.

    returns     an option value containing the first element in the
                sequence that satisfies p, or None if none exists.

用法:

val list = List(("A",1),("B",2),("C",3))

def remove(key:String): Option[Int] = list.find(_._1 == key)

remove("B")
// Some((B,2))

remove("D")
// None

答案 2 :(得分:0)

val list = List(1 -> 'a, 2 -> 'b, 2 -> 'c)

val removal = list find (_._1 == 2)
  // Option[(Int, Symbol)] = Some((2,'b))
val newList = list diff removal.toList
  // List[(Int, Symbol)] = List((1,'a), (2,'c))

diff将只删除参数列表中找到的每个元素的第一个实例,而不是filter