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

Re: "ocaml_beginners"::[] Questions about types

Expand Messages
  • William D. Neumann
    ... OCaml does not allow you to reuse labels in records, unless you enclose the reused ones in a different module. So the way you have it there, the ability
    Message 1 of 2 , Mar 7, 2006
    • 0 Attachment
      On Tue, 7 Mar 2006, [ISO-8859-1] MaurĂ­cio wrote:

      > Could you help me with types? Suppose I have:
      >
      > type a = {b:float;c:int};;
      > type a2 = {b:float;c:int};;
      >
      > When I write {b=3.5;c=2};; ocaml understands I want something of type
      > a2. How do I represent an element of type a?

      OCaml does not allow you to reuse labels in records, unless you enclose
      the reused ones in a different module. So the way you have it there,
      the ability to create an item of type a is lost to you. If you really
      want to do that you'd need to do something like:

      module A =
      struct
      type a = {b:float;c:int}
      end ;;
      module A : sig type a = { b : float; c : int; } end
      # type a2 = {b:float;c:int};;
      type a2 = { b : float; c : int; }
      # let x = {b=3.5;c=2};;
      val x : a2 = {b = 3.5; c = 2}
      # let y = {A.b=3.5;c=2};;
      val y : A.a = {A.b = 3.5; A.c = 2}

      > Could I get something like the code below to be legal?
      >
      > type v = A of {b:float;c:int} | F of float;;

      All you need to do is declare a type alias for the record first:

      # type a2 = {b:float;c:int};;
      type v = A of a2 | F of float;;
      type a2 = { b : float; c : int; }
      # type v = A of a2 | F of float
      # let z = A {b=1.2; c=10}
      let w = F 8.;;
      val z : v = A {b = 1.2; c = 10}
      val w : v = F 8.

      William D. Neumann

      ---

      "There's just so many extra children, we could just feed the
      children to these tigers. We don't need them, we're not doing
      anything with them.

      Tigers are noble and sleek; children are loud and messy."

      -- Neko Case

      Life is unfair. Kill yourself or get over it.
      -- Black Box Recorder

      [Non-text portions of this message have been removed]
    Your message has been successfully submitted and would be delivered to recipients shortly.