转换路径图 - >像地图一样进入树的价值

时间:2013-01-04 14:35:44

标签: scala functional-programming

将带有嵌套路径的行作为键,如:

Map(
  "manufacturer" -> "Magnavox",
  "processor.address-space" -> 8,
  "gpu.processor.address-space" -> 8,
  "processor.speed" -> 150
)

如何成为一个惯用的Scala,用于根据路径对值进行分组,将其转换为:

Map(
  "gpu" -> Map(
             "processor" -> Map("address-space" -> 8)
           ),
  "processor" -> Map(
                   "speed" -> 150,
                   "address-space" -> 8
                 ),
  "manufacturer" -> "Magnavox"
)

注意:所有键都是 leaf 路径,因此,在这种情况下,不允许gpu -> "something"作为输入。

1 个答案:

答案 0 :(得分:2)

def group( m: Map[String, Any] ): Map[String, Any] = {
  def groupImpl( dic: Map[Array[String], Any] ): Map[String, Any] = {
    dic.groupBy(_._1.head).mapValues{ dic: Map[Array[String], Any] =>
      require( !dic.isEmpty)
      if ( dic.size == 1 && dic.head._1.size == 1) {
        dic.head._2
      }
      else {
        groupImpl(
          dic.map{ case (k,v) => 
            require(!k.tail.isEmpty)
            k.tail -> v
          }
        )
      }
    }
  }
  groupImpl( m.map{ case (k,v) => k.split("\\.") -> v} )
}

一些测试:

scala>
group(
  Map(
    "manufacturer" -> "Magnavox",
    "processor.address-space" -> 8,
    "gpu.processor.address-space" -> 8,
    "processor.speed" -> 150,
    "gpu.processor.foo" -> "bar"
  )
)

res2: Map[String,Any] = Map(manufacturer -> Magnavox, processor -> Map(speed -> 150, address-space -> 8), gpu -> Map(processor -> Map(foo -> bar, address-space -> 8)))