Browse thread
Polymorphic variants question
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | David Allsopp <dra-news@m...> |
| Subject: | RE: [Caml-list] Re: Polymorphic variants question |
-----Original Message-----
From: skaller [mailto:skaller@users.sourceforge.net]
Sent: 01 September 2006 20:00
> On Fri, 2006-09-01 at 14:33 -0400, Chris King wrote:
> > On 9/1/06, David Allsopp <dra-news@metastack.com> wrote:
<snip>
> By using:
>
> let id = function `A -> `A | `C -> `C
>
> the compiler knows (id x) can include `A
> and it can include `C, the case
>
> (true, `B)
>
> being returned says the return type can also be `B.
> So the return type can be bool followed by `A, `B, or `C.
>
> Hope that makes sense :)
Which is my understanding too - the type of id is [< `A | `C] -> [> `A | `C]
which allows x to be "used" in a [> `A | `B | `C] context without actually
changing the type of x while type inference is going on. Which, I guess I
should've spotted, means I can write:
let f (x : [`A | `C]) : bool * [`A | `B | `C] =
if x = `A
then (true, `B)
else (false, (x :> [`A | `B | `C]))
Which eliminates id and keeps the whole thing done in the type system
(whilst an identity function I'm sure is spotted and removed by the
compiler, it's a shame to have it there just to keep the type checker
happy!).
Incidentally, if I use an annotation free version
let f x = if x = `A then (true, `B) else (false, (x : [< `A | `C] :> [> `A |
`C]))
then the inferred type of x is [< `A | `C > `A ] ... what does that mean?
> --
> John Skaller <skaller at users dot sf dot net>
> Felix, successor to C++: http://felix.sf.net
Thanks for the help! (incidentally, I don't call labels A, B, C, ... in real
code, honest!)