Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Getting rid of impossible polymorphic variant tags from infered types
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Claudio Sacerdoti Coen <sacerdot@c...>
Subject: Re: [Caml-list] Getting rid of impossible polymorphic variant tags from infered types
> type foo = [ `Foo | `Bar | `Fnord ]
> type foo_flat = [ `Foo | `Bar ]
> 
> let f' l =
>   let f_r (v: foo) (init: foo_flat list) =
>     match v with
>     | `Fnord -> init
>     | _ -> Obj.magic v :: init
>   in
>   List.fold_right f_r l []

 There is no need for Obj.magic:

type foo_flat = [ `Foo | `Bar ]
type foo = [ foo_flat | `Fnord ]
let f_r (v : foo) (init : foo_flat list) =
 match v with
   `Fnord -> init
 | #foo_flat as v -> v :: init
 ;;
type foo = [ `Bar | `Fnord | `Foo ]
type foo_flat = [ `Bar | `Foo ]
val f_r : foo -> foo_flat list -> foo_flat list

 Since the list `Foo | `Bar of variants is written only once,
 the code is also reasonably extensible. Of course it is still not
 what you want.




 If you really need to exclude the `Fnord value at compile time, an
 alternative solution is to use phantom types:

type 'a foo = [ `Foo | `Bar | `Fnord ]
let f_r (v : 'a foo) (init : ([> `NoFnord] foo) list) =
 match v with
   `Fnord -> init
 | _ -> v :: init
 ;;
type 'a foo = [ `Bar | `Fnord | `Foo ]
val f_r : 'a foo -> ([> `NoFnord ] as 'b) foo list -> 'b foo list

The `NoFnord variant explicitly tells that the Fnord value is not allowed.
Notice how the first parameter does not have to satisfy this restriction,
while the second one has to. As usual, you need to use modules to enforce
that a value of type `Foo has type [`NoFnord] foo whereas a value of type
`NoFnord has NOT type [`NoFnord].

					Regards,
					C.S.C.

-- 
----------------------------------------------------------------
Real name: Claudio Sacerdoti Coen
PhD Student in Computer Science at University of Bologna
E-mail: sacerdot@cs.unibo.it
http://www.cs.unibo.it/~sacerdot
----------------------------------------------------------------

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners