22

想象一下,我Map[String, String]在 Scala 中有一个。

我想匹配地图中的全套键值对。

这样的事情应该是可能的

val record = Map("amenity" -> "restaurant", "cuisine" -> "chinese", "name" -> "Golden Palace")
record match {
    case Map("amenity" -> "restaurant", "cuisine" -> "chinese") => "a Chinese restaurant"
    case Map("amenity" -> "restaurant", "cuisine" -> "italian") => "an Italian restaurant"
    case Map("amenity" -> "restaurant") => "some other restaurant"
    case _ => "something else entirely"
}

编译器抱怨thulsy:

error: value Map is not a case class constructor, nor does it have an unapply/unapplySeq method

目前对 a 中的键值组合进行模式匹配的最佳方法是Map什么?

4

6 回答 6

11

您可以使用flatMap提取您感兴趣的值,然后匹配它们:

List("amenity","cuisine") flatMap ( record get _ ) match {
  case "restaurant"::"chinese"::_ => "a Chinese restaurant"
  case "restaurant"::"italian"::_ => "an Italian restaurant"
  case "restaurant"::_            => "some other restaurant"
  case _                          => "something else entirely"
}

请参阅此片段页面上的 #1 。

您可以检查任意列表是否具有特定,如下所示:

if ( ( keys flatMap ( record get _ ) ) == values ) ...

请注意,即使地图中可能不存在键,上述方法仍然有效,但如果键共享某些值,您可能想要使用map而不是在值列表中使用/flatMap明确表示。例如,在这种情况下,如果“amenity”可能不存在,而“cuisine”的值可能是“restaurant”(这个例子很愚蠢,但在另一个上下文中可能不是),那么将是模棱两可的。SomeNonecase "restaurant"::_

此外,值得注意的是,它的case "restaurant"::"chinese"::_效率略高于case List("restaurant","chinese")后者,因为后者不必要地检查这两个之后是否没有更多元素。

于 2012-11-24T11:01:02.090 回答
7

您可以只查找有问题的值,将它们放在一个元组中,然后对其进行模式匹配:

val record = Map("amenity" -> "restaurant", "cuisine" -> "chinese", "name" -> "Golden Palace")
(record.get("amenity"), record.get("cuisine")) match {
    case (Some("restaurant"), Some("chinese")) => "a Chinese restaurant"
    case (Some("restaurant"), Some("italian")) => "an Italian restaurant"
    case (Some("restaurant"), _) => "some other restaurant"
    case _ => "something else entirely"
}

或者,您可以进行一些嵌套匹配,这可能会更简洁:

val record = Map("amenity" -> "restaurant", "cuisine" -> "chinese", "name" -> "Golden Palace")
record.get("amenity") match {
  case Some("restaurant") => record.get("cuisine") match {
    case Some("chinese") => "a Chinese restaurant"
    case Some("italian") => "an Italian restaurant"
    case _ => "some other restaurant"
  }
  case _ => "something else entirely"
}

请注意,它map.get(key)返回一个(在这种情况下 ValueType 将是 String),因此如果映射中不存在该键Option[ValueType],它将返回而不是抛出异常。None

于 2012-11-23T23:06:06.213 回答
6

模式匹配不是你想要的。您想查找 A 是否完全包含 B

val record = Map("amenity" -> "restaurant", "cuisine" -> "chinese", "name" -> "Golden Palace")
val expect = Map("amenity" -> "restaurant", "cuisine" -> "chinese")
expect.keys.forall( key => expect( key ) == record( key ) )

编辑:添加匹配条件

这样您就可以轻松添加匹配条件

val record = Map("amenity" -> "restaurant", "cuisine" -> "chinese", "name" -> "Golden Palace")

case class FoodMatcher( kv: Map[String,String], output: String )

val matchers = List( 
    FoodMatcher(  Map("amenity" -> "restaurant", "cuisine" -> "chinese"), "chinese restaurant, che che" ),
    FoodMatcher(  Map("amenity" -> "restaurant", "cuisine" -> "italian"), "italian restaurant, mama mia" )
)

for {
    matcher <- matchers if matcher.kv.keys.forall( key => matcher.kv( key ) == record( key ) )
} yield matcher.output

给出:

List(chinese restaurant, che che)

于 2012-11-24T02:56:48.833 回答
2

我发现以下使用提取器的解决方案与案例类最相似。不过,它主要是句法肉汁。

object Ex {
   def unapply(m: Map[String, Int]) : Option[(Int,Int) = for {
       a <- m.get("A")
       b <- m.get("B")
   } yield (a, b)
}

val ms = List(Map("A" -> 1, "B" -> 2),
    Map("C" -> 1),
    Map("C" -> 1, "A" -> 2, "B" -> 3),
    Map("C" -> 1, "A" -> 1, "B" -> 2)
    )  

ms.map {
    case Ex(1, 2) => println("match")
    case _        => println("nomatch")
}
于 2016-10-10T16:54:52.823 回答
2

因为,尽管同意所有其他答案都非常明智,但我很想看看实际上是否有一种使用地图进行模式匹配的方法,我将以下内容放在一起。它使用与最佳答案相同的逻辑来确定匹配。

class MapSubsetMatcher[Key, Value](matcher: Map[Key, Value]) {
  def unapply(arg: Map[Key, Value]): Option[Map[Key, Value]] = {
    if (matcher.keys.forall(
      key => arg.contains(key) && matcher(key) == arg(key)
    ))
      Some(arg)
    else
      None
  }
}

val chineseRestaurant = new MapSubsetMatcher(Map("amenity" -> "restaurant", "cuisine" -> "chinese"))
val italianRestaurant = new MapSubsetMatcher(Map("amenity" -> "restaurant", "cuisine" -> "italian"))
val greatPizza = new MapSubsetMatcher(Map("pizza_rating" -> "excellent"))

val record = Map("amenity" -> "restaurant", "cuisine" -> "chinese", "name" -> "Golden Palace")
val frankies = Map("amenity" -> "restaurant", "cuisine" -> "italian", "name" -> "Frankie's", "pizza_rating" -> "excellent")


def matcher(x: Any): String = x match {
  case greatPizza(_) => "It's really good, you should go there."
  case chineseRestaurant(matchedMap) => "a Chinese restaurant called " +
    matchedMap.getOrElse("name", "INSERT NAME HERE")
  case italianRestaurant(_) => "an Italian restaurant"
  case _ => "something else entirely"
}

matcher(record)
// a Chinese restaurant called Golden Palace
matcher(frankies)
// It's really good, you should go there.
于 2017-01-11T22:39:38.900 回答
2

另一个要求您指定要提取的键并允许您匹配值的版本如下:

class MapIncluding[K](ks: K*) {
  def unapplySeq[V](m: Map[K, V]): Option[Seq[V]] = if (ks.forall(m.contains)) Some(ks.map(m)) else None
}

val MapIncludingABC = new MapIncluding("a", "b", "c")
val MapIncludingAAndB = new MapIncluding("a", "b")

Map("a" -> 1, "b" -> 2) match {
  case MapIncludingABC(a, b, c) => println("Should not happen")
  case MapIncludingAAndB(1, b) => println(s"Value of b inside map is $b")
}
于 2017-08-08T13:20:55.043 回答