mattjbray / ocaml-decoders

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

Helper module for tuples #76

Open benbellick opened 2 weeks ago

benbellick commented 2 weeks ago

Hi Matt,

Thinking it could be useful to have something like:

module TupleHelpers : sig 
  val tuple2 : 'a decoder -> 'b decoder -> ('a, 'b) decoder
  val tuple3 : 'a decoder -> 'b decoder -> 'c decoder -> ('a, 'b, 'c) decoder
  val tuple4 : 'a decoder -> 'b decoder -> 'c decoder -> 'd decoder -> ('a, 'b, 'c, 'd) decoder
end = struct <...implementation...> end

The value here is that the example from the uncons part of the documentation:

let (>>=::) fst rest = uncons rest fst

let decoder : (string * bool * int list) decoder =
  string >>=:: fun the_string ->
  bool >>=:: fun the_bool ->
  list int >>= fun the_ints ->
  succeed (the_string, the_bool, the_ints)

could be rewritten as:

let decoder : (string * bool * int list) decoder = tuple3 string bool (list int)

which seems a bit simpler. Then if you go into something more complicated than 4, you would use the more complex monadic uncons operation.

If you agree that this is a good idea, I'll submit a PR :)

benbellick commented 2 weeks ago

Of course the implementation would assume that a tuple is encoded as a list. Perhaps the functions could also take in a boolean flag that determines if the presence of extra items after the end of the tuple should cause a failure or not.

benbellick commented 2 weeks ago

Also, then a decoder for e.g.

type x = Cstr of (int * string * bool * (int list))

would become

let x = 
  let+ i, s, b, l = D.field "Cstr" (tuple4 int string bool (list int)) in 
  Cstr(i,s,b,l)