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

13875accessing record types

Expand Messages
  • Jean Saint-Remy
    Apr 15, 2013

      I am working on a no-frills database application, and wanted to better understand the nullary constructors.
       There are some examples in the literature, but the details are scarce. Most of the time, we don't access types
      directly. They are declared as memory containers so that data can be "safely" allocated, and we use data structures

      type db =
        | Person of entry
        | Weekly of sched
      and entry =

            first_name : string;
            last_name : string;
      and sched =

             date : float;
             starting : float;
             ending : float;
        } ;;
      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.

      There is also an idiomatic short-hand form

      let molly = Person { first_name = "Molly"; last_name = "Peterson"; } ;;

      The type engine understands that there are two fields of type string.

      It seems we are creating an enumerated type, and these are declared just like records with (expr : type) syntax.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.

      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?

      With kind regards,


      [Non-text portions of this message have been removed]
    • Show all 6 messages in this topic