Hacker News new | ask | show | jobs
by mrkgnao 3098 days ago
How does record access work? Is it via generated record accessor functions (pretty crappy, used by Haskell) or does OCaml now have true row types (as in PureScript (and perhaps Elm))? Can you have multiple types with the same record field name?
1 comments

The "inlined" record can only be accessed locally and can not be returned as a single value (See manual here: http://caml.inria.fr/pub/docs/manual-ocaml/extn.html#sec271). In general, multiple types can have the same record fields/constructor names. The typechecker uses type information to figure things out in case of conflicts.

For example:

  type t1 = { foo : int ; bar : int }
  type t2 = { foo : string ; baz : int }

  let x = { foo = 2 ; bar = 2 }
  let y = { foo = "foo" ; baz = 3 }

  let f x = x.foo ^ "x" (* In case of doubt, uses the last one defined *)
  let g (x : t1) = x.foo + 1 (* Uses the types to find the right one *)
  let h { foo ; bar } = foo + bar (* Figure things out using the fields *)
(Of course this is an extreme example, good code should be clearer than that :p)

When a field "foo" comes from a type t in a module M (M.t), you can either use type disambiguation as above or qualify accesses : x.M.foo. All this also works with ADTs.