The syntax "{}" like object in JS has what meaning?

Hi :slight_smile:

I’m learning OCaml and would like to ask some syntax questions.

When I try to access two types defined (line 1 and 4), any error is not occurred but if I try to access type tt which is defined in line 6, OCaml interpreter says that tt is unbound.

  1 type t = Int of int | Float of float
  2
  3 module M = struct
  4     type t = Module_Int of int | Module_Float of float
  5
  6     type tt = {
  7         foo: string
  8     }
  9
 10     let add x y = x+y
 11 end
 12
 13 let _ =
 14     let a = Int 1 in (* OK *)
 15     let b = M.Module_Int 1 in (* OK *)
 16     let c = M.foo "str" in ();; (* Not OK *)
~ 
  1. What is the keyword of the types in line 6 ? It looks like object type in JS.

  2. Why OCaml interpreter detects error? what’s the reason?

Thank you :slight_smile:

Hi,

tt is a type record. In order to use it, you have to create a value of this type :

let v = M.{ foo = "str" }

Then you can access its fields by v.M.foo or simply v.foo if module M is open in you environment

If I can add something,foo doesn’t exists beyond being a field of a value of type tt.
It is like write User.name in Java to access the field name of a instance of class User, when you should before build a value User user = ... and then user.name.

1 Like