Merging mappings together #1079
-
I'm currently writing a template in pkl that needs to take several map1 = new Mapping {
["foo"] {
"a"
"b"
"c"
}
["bar"] {
"d"
"e"
"f"
}
}
map2 = new Mapping {
["foo"] {
"p"
"q"
"r"
}
["baz"] {
"x"
"y"
"z"
}
}
l1 = new Listing {
map1
map2
}
result = mergeMaps(l1) where result becomes: result {
["foo"] {
"a"
"b"
"c"
"p"
"q"
"r"
}
["bar"] {
"d"
"e"
"f"
}
["baz"] {
"x"
"y"
"z"
}
} This is my best attempt at writing function mergeMaps(l: Listing<Mapping>): Mapping =
l.fold(Map(), (m, maps) ->
maps.toMap().map((k, v) ->
if (m.containsKey(k)) (m[k]) { ...v } else m.put(k, v))).toMapping() But this results in an evaluation error:
I'm not sure how to proceed at this point. Any suggestions? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Give this a shot: function mergeMaps(l: Listing<Mapping<Any, Listing>>): Mapping<Any, Listing> =
l.fold(new Mapping<Any, Listing> {}, (acc, elem) ->
elem.fold(acc, (acc, k, v) ->
(acc) { [k] { ...v } }
)
) Shadowing |
Beta Was this translation helpful? Give feedback.
Give this a shot:
Shadowing
acc
here is a little naughty, but it does work. You also need a little more typing on your input, see https://pkl-playground.vercel.app/?share=these-hearing-bee for everything together.