我有一个包含Salesman,Product,Location,SalesValue数据的文件
例如:
Bob, Carrots, United States, 200
Bill, Potatoes, England, 100
Bob, Oranges, England, 50
Bob, Carrots, United States, 20
Run Code Online (Sandbox Code Playgroud)
可以使用以下代码将SalesValue简洁地累积到perl中的哈希哈希值中
while(<>){
@cols = split(/,/);
$vals {$cols[0]} {$cols[1]} {$cols[2]} += $cols[3];
}
Run Code Online (Sandbox Code Playgroud)
有没有人有任何建议如何创建地图地图的地图,加上积累,最好在scala中实现?
我建议将这些地图合并为一个monoid-append操作.
首先,我们将地图地图的地图创建为单个元素:
val input = """Bob, Carrots, United States, 200
|Bill, Potatoes, England, 100
|Bob, Oranges, England, 50
|Bob, Carrots, United States, 20""".stripMargin.lines.toList
val mmm = input.map(_.split(", "))
.map { case Array(n, g, c, v) => Map(n -> Map(g -> Map(c -> v.toInt))) }
Run Code Online (Sandbox Code Playgroud)
mmm是类型List[Map[String, Map[String, Map[String, Int]]]]:
List[Map[String,
Map[String,
Map[String, Int]]]]
Run Code Online (Sandbox Code Playgroud)
然后我们可以suml使用像scalaz或的库cats:
import scalaz._, Scalaz._
println(mmm.suml)
Run Code Online (Sandbox Code Playgroud)
这将打印(未提供):
Map(Bill -> Map(Potatoes -> Map(England -> 100)),
Bob -> Map(Oranges -> Map(England -> 50),
Carrots -> Map(United States -> 220)))
Run Code Online (Sandbox Code Playgroud)
为了帮助了解.suml操作背后的情况,我会无耻地建议查看我去年制作的演示文稿https://speakerdeck.com/filippovitale/will-it-blend-scalasyd-february-2015
编辑
我们还可以看到我们的地图地图地图,Foldable并使用foldMap相同的结果:
input.map(_.split(", "))
.foldMap{ case Array(n, g, c, v) => Map(n -> Map(g -> Map(c -> v.toInt))) }
Run Code Online (Sandbox Code Playgroud)