【发布时间】:2015-03-14 20:13:29
【问题描述】:
我有一个这样创建的数据结构:
// [Measure -> [Installation -> [Year -> [Month -> [Day -> [Hour -> BigDecimal] ]]]]]
private var dayList = new mutable.HashMap[String, mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]]]]]()
这样做的原因是我希望能够查找此映射以获取我的数据。
然而,在 scala 中插入这个数据结构我得到这样的东西:
dayList.get(col) match {
case Some(measureLook) =>
measureLook.get(installation) match {
case Some(instaLook) =>
instaLook.get(tempYear) match {
case Some(yearLook) =>
yearLook.get(tempMonth) match {
case Some(monthLook) =>
monthLook.put(tempDay, hourCounter)
case None =>
val m = new mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]()
m.put(tempDay, hourCounter)
yearLook.put(tempMonth, m)
}
case None =>
val y = new mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]]()
val m = new mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]()
m.put(tempDay, hourCounter)
y.put(tempMonth, m)
instaLook.put(tempYear, y)
}
case None =>
val in = new mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]]]()
val y = new mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]]()
val m = new mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]()
m.put(tempDay, hourCounter)
y.put(tempMonth, m)
in.put(tempYear, y)
measureLook.put(installation, in)
}
case None =>
val me = new mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]]]]()
val in = new mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]]]()
val y = new mutable.HashMap[Int, mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]]()
val m = new mutable.HashMap[Int, mutable.HashMap[Int, BigDecimal]]()
m.put(tempDay, hourCounter)
y.put(tempMonth, m)
in.put(tempYear, y)
me.put(installation, in)
dayList.put(col, me)
}
这对我来说是疯狂的代码量。而且我觉得这可以以某种方式缩短,但我没有看到解决方案。
因为我必须查找元素,如果它存在,那么我可以很容易地插入到元素中。
但是,如果链中某处的元素不存在,那么我必须创建元素,当然还有所有子元素,正如您在上面的代码中看到的那样。
您有什么想法可以让我更干净地做到这一点,或者为此使用更有组织的数据结构吗?
【问题讨论】:
-
用于理解。如果您提供一些示例数据,我可以写一个示例。
-
嗯,我有一些来自我正在使用的 MongoDB 的输出。 pastebin.com/12n6Tre7
标签: scala dictionary data-structures pattern-matching