1

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
8
  • 1
    It looks like maybe type aug might be defined as type 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. Commented Jun 17, 2022 at 4:37
  • @Chris I'm sorry for the confusion; There was a typo while translating my code in to a MWE: aug should be a recursive data type using itself, not orig. In such case, isn't type aug = Aug of int * orig not viable? Commented Jun 17, 2022 at 5:02
  • Suggest rewriting gen_dat as let gen_dat () = _cnt := !_cnt + 1; !_cnt. The local let binding is unnecessary. Commented Jun 17, 2022 at 5:48
  • 1
    I’m sure someone will come up with relevant PPX tools. In the meantime, if you have the possibility to modify the orig type, perhaps you could make it a type constructor that takes the dat type as a parameter. Then you’d just have to write a recursive function map_dat : ('a -> 'b) -> 'a aug -> 'b aug (or have it generated by PPX magic), which might be a useful factorization? Commented Jun 17, 2022 at 11:57
  • 1
    I really meant 'a aug -> 'b aug. You’d have only one inductive type, and you’d define orig as unit aug. Commented Jun 17, 2022 at 19:42

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.