4 元组序列到地图的地图的地图
我需要一种更简洁的方法将元组序列转换为地图的地图...... 作为我在 Tuple4
情况下得到的签名:
def tuple4Seq2MapOfMaps[A,B,C,D](seq: Seq[(A,B,C,D)]): Map[A,Map[B,Map[C,D]]]
以下代码显示了我最近的丑陋代码,我坚持使用(类型 A
到 D
任意):
type A = Int
type B = Double
type C = String
type D = Boolean
val tupleSeq = Seq[(A,B,C,D)](
(1,1.0D,"a",true),
(1,1.0D,"b",true),
(1,1.0D,"c",false)
)
val x = tupleSeq.groupBy{ _._1 }.map{ case (k,s) => (k,s.map{ x => (x._2,x._3,x._4) }) }
val y = x.map{ case (k,s) => (k,s.groupBy{_._1}.map{ case (k,s) => (k,s.map{ x => (x._2,x._3) }) }) }
val z = y.map{ case (k1,m) => (k1,m.map{ case (k2,s1) => (k2,s1.groupBy{_._1}.map{ case (k3,s2) => (k3,s2.map{ _._2 }.head) }) }) }
val m = z(1)(1.0D)
println(m("b"))
注意 val z
处 head
的使用。
如果有一种仅适用于 Tuple4
的更简洁的方法,那就太好了,但更有趣的是如何将其推广到 TupleN
(N >= 2)。
有人心里有一个好的方法吗?
谢谢你!
I need a more concise way to transform a sequence of tuples into a map of maps of maps...
As a signature I get in case of Tuple4
:
def tuple4Seq2MapOfMaps[A,B,C,D](seq: Seq[(A,B,C,D)]): Map[A,Map[B,Map[C,D]]]
The following code shows my recent ugly code, I stucked with (type A
to D
arbitrary):
type A = Int
type B = Double
type C = String
type D = Boolean
val tupleSeq = Seq[(A,B,C,D)](
(1,1.0D,"a",true),
(1,1.0D,"b",true),
(1,1.0D,"c",false)
)
val x = tupleSeq.groupBy{ _._1 }.map{ case (k,s) => (k,s.map{ x => (x._2,x._3,x._4) }) }
val y = x.map{ case (k,s) => (k,s.groupBy{_._1}.map{ case (k,s) => (k,s.map{ x => (x._2,x._3) }) }) }
val z = y.map{ case (k1,m) => (k1,m.map{ case (k2,s1) => (k2,s1.groupBy{_._1}.map{ case (k3,s2) => (k3,s2.map{ _._2 }.head) }) }) }
val m = z(1)(1.0D)
println(m("b"))
Note the use of head
at val z
.
It would be nice to have a more concise way for only Tuple4
, but furthermore interesting how to generalize this to TupleN
(N >= 2).
Is there a nice approach in someones mind out there?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我能想到的最好的办法是,
推广到更高数量的元组非常简单...只需添加 mapValues(_groupBy(_._n)....的附加嵌套应用程序。...并相应地调整最终的模式匹配。
完全推广这一点作为任意元组上的函数,可以使用 HLists,但这很可能是比这里需要的更重量级的解决方案,我将把这条攻击路线作为提问者(或其他评论者)的练习;- )。
The best I can come up with is,
Generalizing to tuples of higher arity is quite straightfoward ... just add additional nested applications of mapValues(_groupBy(_._n). ... and adjust the final pattern match accordingly.
Fully generalizing this as a function over tuples of arbitrary arity would be possible using HLists, but that would most likely be a far more heavyweight solution than is needed here. I'll leave this line of attack as an exercise for the questioner (or other commenters ;-).
我建议在元组上隐式:
I'd suggest implicits on the tuples: