Hi,
I’m new to ReScript (and nearly new to functional programming) and I’m trying to convert a flat data structure into a hierarchical one, but cannot figure out how to do this in ReScript (and would be equally stumped in many other strongly-typed languages). I’m an accountant and like to program in my spare time with this as my new pet project!
I’m trying to model a set of financial accounts and the input is an array of data that looks like:
array<(array<String, String, String, String>, int)> //option 1
//or
array<(String, String, String, String, int)> //option 2
for context an element might be:
("Assets", "Non-current assets", "Property", "34 Long Road", 25000000)
and I want to turn this into a nested structure to pass to React for displaying financial statements. The nested structure would look something like this (I’m sure room for improvement):
type rec childType =
| Category(array<account>)
| Account(int)
and account = {name: string, value: int, children: childType}
When using plain javascript I depended on D3.nest (https://github.com/d3/d3-collection#nests) for this purpose, I could depend on this again if needed. However, I’d love solve this in ReScript as I have been struggling for hours. I understand that D3’s nest is weakly-typed, you make assertions about the shape of the data when calling the function, and you get a runtime error if the data does not conform to expectations.
I’ve tried starting with my option 1 above, but I think the problem is the number of Strings in the inner array is not encoded in the type so in a recursive function it is hard to convince ReScript that every element of an array has reached an edge condition at the same time.
I then explored option 2 above, my idea being that a function would be called with (X, X, X, X), then (X, X, X), then (X, X), then (X) recursively, but I think tuples of different sizes are completely different types and I don’t think you can write such a generic function in ReScript. I considered a variant with all four options but that idea exploded with boilerplate and I’d ideally want something that generalised to an arbitrary number of levels of nesting. In C++ I think I could write a recursive template function using parameter packs or fold expressions to achieve this.