Iteration over record attributes in OCaml


#1

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?


#2

Easier as in less boilerplate code? There are two solutions that come to mind:

  1. use polymorphic variants to avoid having to define a new type
  2. 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.


#3

There is a ppx rewriter that should help.

Relevant chapter from Real World OCaml: https://dev.realworldocaml.org/records.html


#4

I know about that library but it doesn’t fit my requirements cause I need attributes-related data at runtime.


#5

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?


#6

Think you might be looking for Hashtbl? What are your other requirements w.r.t. the type?


#7

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.


#8

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.


#9

Yep, Hashtbl looks like the solution for some of my purposes.