在OCaml中考虑产品类型分配

mba*_*768 5 ocaml types product boilerplate

我一般不满意编写这样的代码:

let load_record_field cursor gets geti gett a = function
  | 0x01 -> let c, s = gets () in (a.a_record_uuid <- s; `More_record c)
  | 0x02 -> let c, s = gets () in (a.a_group <- s; `More_record c)
  | 0x03 -> let c, s = gets () in (a.a_title <- s; `More_record c)
  | 0x04 -> let c, s = gets () in (a.a_username <- s; `More_record c)
  | 0x07 -> let c, t = gett () in (a.a_creation_time <- t; `More_record c)
  .
  .
  .
  | 0xFF -> `End_of_record cursor
Run Code Online (Sandbox Code Playgroud)

我已经最小化了样板,但我想知道是否有任何OCaml魔法让我完全消除它.

zrr*_*zrr 2

这非常简单:只需使用闭包进行设置,然后编写一个函数来抽象出样板文件

let load_record_field cursor gets geti gett a x =
  let frob get set =
     let (c,s) = get () in
     set s; `More_record c
  in
  function
  | 0x01 -> frob gets (fun s -> a.a_record_uuid <- s)
  | 0x02 -> frob gets (fun s -> a.a_group <- s)
  | 0x03 -> frob gett (fun s -> a.a_title <- s)
  ...
Run Code Online (Sandbox Code Playgroud)

等等。

如果您使用像 Jane Street 的 fieldslib 这样的宏包,您可以做得更好。这会生成一流的字段,以及自动生成的 setter 和 getter。这意味着您不必每次都手动构建闭包。