mattjbray / ocaml-decoders

Elm-inspired decoders for Ocaml
https://mattjbray.github.io/ocaml-decoders/
Other
84 stars 8 forks source link

How to define mutually recursive decoders? #61

Closed dboris closed 1 year ago

dboris commented 1 year ago

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?

mattjbray commented 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
dboris commented 1 year ago

Yep, that works. Thanks again.