Version française
Home     About     Download     Resources     Contact us    
Browse thread
Pattern matching but no construction?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: William Lovas <wlovas@s...>
Subject: Re: [Caml-list] Pattern matching but no construction?
On Thu, Oct 28, 2004 at 02:34:49PM -0700, Harrison, John R wrote:
> Is there a way to use the OCaml module system to declare an
> abstract type with an implementation as a recursive type in
> such a way that:
> 
>  * You can use the constructors to pattern-match against
> 
>  * You cannot use the constructors to construct values

Indeed, there is!  The relevant keyword is `private'.  See:

    http://caml.inria.fr/ocaml/htmlman/manual021.html#@manual.kwd173

for details.

In your example, we just do:

> For example, suppose I do the following:
> 
>   module type Wibble =
>  (* sig type thing = Integer of int | Boolean of bool *)
      sig type thing = private Integer of int | Boolean of bool
>         val mk_thing : int -> thing
>         val dest_thing: thing -> int
>     end;;
>
> [...]

And then it works as expected:

    # Thing.Integer 5;;
    Cannot create values of the private type Thing.thing
    # let thing = Thing.mk_thing 5;;
    val thing : Thing.thing = Thing.Integer 5
    # match thing with
        Thing.Integer i -> i
      | Thing.Boolean b -> 0;;
    - : int = 5

cheers,
William