jzon icon indicating copy to clipboard operation
jzon copied to clipboard

Encode/decode recursive structure

Open vknez opened this issue 3 years ago • 3 comments

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?

vknez avatar Dec 10 '21 11:12 vknez

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.

nkrkv avatar Dec 10 '21 11:12 nkrkv

Thanks for the quick response!

vknez avatar Dec 10 '21 12:12 vknez

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...

nkrkv avatar Dec 15 '21 09:12 nkrkv