-
This should be a straightforward-enough problem but I just can't wrap my head around it, so here I am asking help from the community: How to turn a record like this:
into something like this:
This is not the entire input of course, but the characteristics of the input record is that the nesting depth for every top-level key is the same (in this example, the depth is 3, i.e. you need a path of exactly length 3 to get to the "value"). The use case is essentially converting a declarative configuration to a script consisting of imperative "uci set" commands. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi! Here is a possibility: I just wrote a recursive function which traverses records and gather all leafs as an array:
I think it's slightly different from yours, because you stop at a specific depth, but it shouldn't be too difficult to tune: you can just add an additional parameter to @@ -29,9 +29,9 @@ let leafs
]
```
"%
- | { .. } -> Array (Array Dyn)
+ | std.number.Nat -> {..} -> Array (Array Dyn)
=
- let rec leafs_aux
+ let rec leafs_aux
| doc m%"
Auxiliary variant of `leafs`.
@@ -41,8 +41,9 @@ let leafs
record). Returns the set of leafs of this field, represented as an array
of paths.
"%
- | Array String -> Dyn -> Array (Array Dyn) = fun path value =>
- if !(std.is_record value) then
+ | Array String -> std.number.Nat -> Dyn -> Array (Array Dyn)
+ = fun path depth value =>
+ if !(std.is_record value) || depth == 0 then
# If we reached a leaf, we just append the value to the current path,
# and return an array with a single element
[std.array.append value path]
@@ -55,7 +56,7 @@ let leafs
(
fun { field, value } =>
let new_path = std.array.append field path in
- leafs_aux new_path value
+ leafs_aux new_path (depth - 1) value
)
# Now we have an array of array of fields (each subfield might have
# several leafs itself), so we finally flatten it
@@ -88,4 +89,4 @@ let leafs
},
},
}
-|> leafs
+|> leafs 2 The second version stops at max depth |
Beta Was this translation helpful? Give feedback.
Hi!
Here is a possibility: I just wrote a recursive function which traverses records and gather all leafs as an array: