nkrkv / jzon

ReScript library to encode and decode JSON data with type safety.
https://nkrkv.github.io/jzon/
Other
76 stars 4 forks source link

Encode/decode recursive structure #15

Open vknez opened 2 years ago

vknez commented 2 years ago

Hi. First of all, thanks for this elegant library. I'm eager to use it, but I have issues when trying to use it to deal with the following type:

type rec node = {
  id: string,
  children: array<node>,
}

When I try to declare the codecs for this, there's an error because of the recursive children field. let rec syntax isn't supported here. Does Jzon support recursive structures at all?

nkrkv commented 2 years ago

Ouch, never thought about recursive records. At the first glance, I see no easy way to express it other than a hand-crafted codec (that wouldn’t benefit from Jzon facilities). I’ll think deeper about how this can be achieved because it has to be possible.

vknez commented 2 years ago

Thanks for the quick response!

nkrkv commented 2 years ago

Generalizing the problem I see it’s a little more complex than recursive records. For the example provided it should be possible to implement something like Jzon.fieldRec as an addition to the regular Jzon.field but it will not sustain “transitive” chains of recursion. For example, where recordA has a nested recordB that has a nested recordC that has a nested recordA. In such case a codec for recordA should be defined before recordC and vice versa at the same time. ReScript does not support lookahead, so it will fail.

Thinking about more general solution...