(anonymous?) polymorphic records

Is there a way to avoid to create records only to preserve polymorphism ?

Say, for this, in haskell style

h :: (forall r. (r -> a) -> (f r -> f b)) -> f a -> f b
h malg = malg id

You can use objects, they can have polymorphic methods:

let f (id:<f:'a. 'a -> 'a>) = id#f 0, id#f "zero"
1 Like

The following doesn’t help reducing the syntactic noise, but note that when using a record for non-prenex polymorphism like this, your record has only one field and is immutable, so (with a recent enough OCaml) you can unbox it and get rid of the runtime overhead:

type ('a, 'b) fwrap = { f : 'r. ('r -> 'a) -> 'r list -> 'b list } [@@unboxed]

let apply_id : type a b. (a, b) fwrap -> a list -> b list =
  fun w xs -> w.f Fun.id xs
(* is compiled the same as just: *)
let apply_id_magic : type a b. (a, b) fwrap -> a list -> b list =
  fun w xs -> (Obj.magic w) Fun.id xs

let mwrap : type a. (a, a) fwrap = { f = List.map }
(* is compiled to nothing at all (alias of List.map). *)

Not sure if I understood the gist of this comment, but, as written, this will almost certainly cause a segfault if executed.

Cheers,
Nicolas

Ah, I understood it now, it is illustrating the unboxed attribute, makes sense. Sorry for the noise.

Cheers,
Nicolas