Version française
Home     About     Download     Resources     Contact us    
Browse thread
# and polymorphic variants
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Brian Rogoff <bpr@b...>
Subject: Re: # and polymorphic variants
You need to use a "let rec" so that the function f1 is defined in f (or
replace the "and"s with "let"s) and use aliases. The first should be
obvious, the need for aliases seems necessary to get the coercion. Is 
this what you want?

type t1 = [ `A of int ];;
type t2 = [ `B of string ];;
type t = [ `A of int | `B of string ];;

let rec f1 (`A (x : int)) =
        print_int x 
and f2 (`B (x : string)) =
        print_string x 
and f (x : t) =
        match x with
        | #t1 as x -> f1 x 
        | #t2 as x -> f2 x;;

-- Brian

On Thu, 1 Feb 2001, Juergen Pfitzenmaier wrote:

> Dear ocaml users,
> consider the following example:
> 
> type t1 = [ `A of int ];;
> type t2 = [ `B of string ];;
> type t = [ `A of int | `B of string ];;
> 
> let f1 (`A (x : int)) =
> 	print_int x
> and f2 (`B (x : string)) =
> 	print_string x
> and f (x : t) =
> 	match x with
> 	| #t1 -> f1 x      (* this is not allowed !! *)
> 	| #t2 -> f2 x;;
> 
> The compiler can't constrain the type t of x to t1/t2 in the call to f1/f2.
> And an coercion like in
>     ...
> 	match x with
> 	| #t1 -> f1 (x :> t1)
>     ...
> is not allowed. So I see only one solution:
>     ...
> 	match x with
> 	| #t1 -> f1 (Obj.magic(x) :> t1)   (* I don't like magic *)
>     ...
> But I would like to see something clean like giving a name to the # pattern
>     ...
> 	match x with
> 	| #t1 y -> f1 y    (* (y : t1) would have the same value as x *)
>     ...
> or like
>     ...
> 	match x with
> 	| #t1 -> f1 x      (* x is constrained to type t1 *)
>     ...
> 
> Any comments ?
> 
> -- pfitzen
> 
> 
>