Function argument polymorphism

OCaml functions aren’t allowed to be polymorphic over record fields this way. However, this kind of polymorphism is a classic use case for objects! Instead of records you can create two objects:

let rec1 =
  object
    method prop1 = 1
    method prop3 = 2
  end
let rec2 =
  object
    method prop2 = 3
    method prop3 = 4
  end
let func r = r#prop3
let x = func rec1
let y = func rec2

If you check the types you’ll see that func is polymorphic, and accepts any object with a prop3 method:

val func : < prop3 : 'a; .. > -> 'a

3 Likes