Loading ...
Sorry, an error occurred while loading the content.

13877Re: "ocaml_beginners"::[] accessing record types

Expand Messages
  • Toby Kelsey
    Apr 15, 2013
      On 15/04/13 18:43, Jean Saint-Remy wrote:
      > let molly : db = Person { first_name = "Molly"; last_name = "Peterson"; }
      > and week1 : db = Weekly { date = 1355062480.; starting = 1355103310.; ending = 1355122250.; } ;;
      > The molly and week1 statements can also be written separately. That would be currying.

      No, currying is treating a function which can take multiple arguments as taking
      one. Here molly and week1 are separate values, each of type db.
      Usually (name : type) is used as a hint to the compiler about the type to use,
      but in this case it is not necessary as the constructors Person and Weekly tell
      it the type.
      OCaml can almost always work out the correct type without a hint. Constructors
      don't need hints.

      To access the fields, can we use molly.first_name or molly.last_name besides
      writing a function "match x with"
      > to decompose the fields? I have read many programs where these types are simply plugged into data structures, as
      > long as the types are matching, everything works as expected. Obviously mixed type of string and float would become
      > a tuple or a hash and won't work with lists or arrays which expect one kind of an object. It seems there is a leap of
      > faith, the types are declared and then we just work with data structures with types being mere place holders.

      There is no faith required. The compiler works out (infers) all the types, and
      if it can't it gives you a compiler error.

      > Declaring a "db" type with 5 fields is very simple and works well. If we want String.length (molly.first_name) we
      > need to wrap the field in a data structure and access the elements. Is that all there is to the constructors? It took me
      > a while to figure out how to get from the type declaration to the instance of molly, until I hit upon the (expr : type)
      > with parenthesis required in the literature. OCaml core reference goes right away into pattern matching, so I could
      > not apply the constructor. Would you be so kind and explain the nullary constructor in a greater detail?

      There are some good tutorials around. To understand constructors and how to use
      'match' I would suggest you start with
      <http://ocaml.org/tutorials/data_types_and_matching.html>. If you have
      problems with specific examples post them here.

    • Show all 6 messages in this topic