English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
Re: [Caml-list] variant with tuple arg in pattern match?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-04-10 (10:44)
From: reig@d...
Subject: Re: [Caml-list] variant with tuple arg in pattern match?
Michel Mauny wrote:

> Well, as far as I understand, there is an interaction with
> pattern-matching. Consider the following example:
>   type 'a t =
>     Int : int -> int t
>   | Bool : bool -> bool t
>   | Node : 'a t -> 'a t -> 'a t
> This definition implies that data constructors Int and Bool cannot
> appear in the same tree (no way to be at the same time an int t, and a
> bool t, unless being an 'a t, which cannot occur at all).
> [...]

This is how you do it in haskell:

data T a = I Int
	 | B Bool
	 | N (T a) (T a) 
	 | Uncurried (Int,Int)

hugs (a haskell interpreter) reports this:

Main> :i T
-- type constructor
data T a
-- constructors:
I :: Int -> T a
B :: Bool -> T a
N :: T a -> T a -> T a
Uncurried :: (Int,Int) -> T a

Of course, you can have trees with bools and ints:

Main> N (I 1) (B True)
N (I 1) (B True) :: T a

Notice that I has type Int -> T a, not Int -> T Int

The equivalent in ocaml, using Pierre's new syntax, would be:

   type 'a t =
     Int : int -> 'a t
   | Bool : bool -> 'a t
   | Node : 'a t -> 'a t -> 'a t
   | Uncurried : int * int -> 'a t

Moreover, the last part (-> 'a t) is the same for all constructors and
can be omitted like you do in haskell (so that Xavier is happier :)

   type 'a t =
     Int : int
   | Bool : bool
   | Node : 'a t -> 'a t
   | Uncurried : int * int

[I assume there would be no type checking problems for ocaml, but I
don't know for sure]

One other thing changes too: data constructors can be partially
applied in haskell. Ex:

Main> :t N (I 1)
N (I 1) :: T a -> T a

Main> map I [1,2,3]
[I 1,I 2,I 3] :: [T a]

[Don't need to eta expand (\x -> I x)]

Personally, I quite like this feature of haskell compared to ML.

Fermin Reig
To unsubscribe, mail caml-list-request@inria.fr.  Archives: http://caml.inria.fr