Closed dboris closed 1 year ago
There is an example of decoding a mutually-recursive type in the tests: https://github.com/mattjbray/ocaml-decoders/blob/62b2b2981a65147e00d1b7fa63b27f50b5a516f3/test-yojson/main.ml#L80-L90
I'd more typically write this by having the individual decoders take one of them as an argument, then using fix
:
let t2_decoder t1_decoder =
nullable (field "t1" t1_decoder)
|> map (function None -> T2_end | Some t1 -> T2_more t1)
let t1_decoder t1_decoder =
nullable (field "t2" (t2_decoder t1_decoder))
|> map (function None -> T1_end | Some t2 -> T1_more t2)
let t1_decoder = fix t1_decoder
Yep, that works. Thanks again.
A single recursive decoder can be defined using
fix
. What about a pair of decoders that are mutually recursive and must refer to each other?