Please skip the text below and read UPD section
Is is posible to iterate over record’s attributes?
type rec = { a: int,
b: string}
let r = { a = 10;
b = "hello"}
Record.iter r ~f: ...
It looks like I should create a variant type for each record type to use it in the signature of ~f:
function, but I hope there is an easier way to do this.
UPD: Hm, it looks like I asked a bad question. The correct question is: how can I define record types at runtime. And it looks like there is no such ability in OCaml or am I wrong?
1 Like
Easier as in less boilerplate code? There are two solutions that come to mind:
- use polymorphic variants to avoid having to define a new type
- generate an iter function automatically using ppx
For option 2, there may be a ppx rewriter that can do this already out there. Check out Jane streets GitHub repo.
1 Like
I know about that library but it doesn’t fit my requirements cause I need attributes-related data at runtime.
Hm, it looks like I asked a bad question. The correct question is: how can I define record types at runtime. And it looks like there is no such ability in OCaml or am I wrong?
Think you might be looking for Hashtbl? What are your other requirements w.r.t. the type?
I suspect ppx_fields_conv, and functions like Fields.make_creator will do what you need. Take a closer look at the library. You can do a lot of run-time generation of representations of record types using it.
2 Likes
You are right, the type system doesn’t let you define record types after type checking. You’ll want row polymorphism for that, though the only language I know of that implements them right now is Ur/Web.
1 Like
Yep, Hashtbl looks like the solution for some of my purposes.