3

如何在Scala的对列表中惯用搜索?value(element, value)

是否有比以下解决方案更好(也许更简洁和/或更有效)的方法?

code.find(_._1 == 2).get._2

code类型在哪里List[(Int, String)]

scala> val code: List[(Int, String)] = (0, "zero") :: (1, "one") :: (2, "two") :: Nil
code: List[(Int, String)] = List((0,zero), (1,one), (2,two))
scala> code.find(_._1 == 2).get._2
res0: String = two
4

2 回答 2

11

模式匹配呢?

 code.collectFirst{ case(2, x) => x }

这会产生Some(two)你可以进一步map/ fold

于 2013-04-30T09:41:35.663 回答
0

这将做:

scala> code.toMap
res17: scala.collection.immutable.Map[Int,String] = Map(0 -> zero, 1 -> one, 2 -> two)

scala> res17(0)
res18: String = zero
于 2013-04-30T09:38:22.173 回答