Is there a way to efficiently "augment" or attach some more information without much boilerplate?
That is, given types
type orig =
| A
| B of orig
| C of orig * orig
and type dat = int
and type aug =
| AugA of dat
| AugB of dat * aug
| AugC of dat * aug * aug
and functions
let _cnt = ref 0
let gen_dat () =
let _ = _cnt := !_cnt + 1 in
!_cnt
let rec augment (o: orig) : ao =
match o with
| A -> AugA (gen_dat ())
| B o -> AugB (gen_dat (), augment o)
| C (o1, o2) -> AugC (gen_dat (), augment o1, augment o2)
I think this is a trivial structural recursion on its components, and I have to do repeat this type of identical manipulations on several types with 10+ patterns (Multiple augs each with its own augment function associated).
This leads to a long, tedious boilerplate code. Is there a way to abstract away this manipulation in OCaml, e.g., with help of ppx?
asked Jun 17, 2022 at 3:19
Jay Lee
1,9811 gold badge17 silver badges33 bronze badges
lang-ml
augmight be defined astype aug = Aug of int * orig. While there likely is a way to do this with ppx (which I have not mastered nor explored in depth) this might also verge into XY problem territory depending on what you're ultimately trying to achieve.augshould be a recursive data type using itself, notorig. In such case, isn'ttype aug = Aug of int * orignot viable?gen_dataslet gen_dat () = _cnt := !_cnt + 1; !_cnt. The local let binding is unnecessary.origtype, perhaps you could make it a type constructor that takes thedattype as a parameter. Then you’d just have to write a recursive functionmap_dat : ('a -> 'b) -> 'a aug -> 'b aug(or have it generated by PPX magic), which might be a useful factorization?'a aug -> 'b aug. You’d have only one inductive type, and you’d defineorigasunit aug.