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
Unexpected '_a problem
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2006-08-01 (21:15)
From: Andreas Rossberg <AndreasRossberg@w...>
Subject: Re: [Caml-list] Unexpected '_a problem
"Chris King" <colanderman@gmail.com> wrote:
>
> # let create_foo () = object method foo (_: 'a) = () end;;
> val create_foo : unit -> < foo : 'a -> unit > = <fun>
> # let a = create_foo ();;
> val a : < bar : '_a -> unit > = <obj>
>
> the compiler determines a is monomorphic, since 'a is in a
> contravariant position.  But why, when 'a is placed in a covariant
> position:

This has nothing to do with contravariance, nor with subtyping or objects at
all. What you observe is the infamous "value restriction": roughly, a
definition can only be polymorphic when its right-hand side is syntactically
a value (i.e. a function, tuple, constant, etc or combination thereof). In
your case it's an application.

Also note that in the above code, it is the object that would be
polymorphic, not the method! If you want a polymorphic method, the proper
syntax is the following:

# let create_foo () = object method foo : 'a.'a -> unit = fun _ -> () end;;
val create_foo : unit -> < foo : 'a. 'a -> unit > = <fun>
# let a = create_foo ();;
val a : < foo : 'a. 'a -> unit > = <obj>
# a#foo 5; a#foo true;;
- : unit = ()

Here, `a' is a monomorphic object with a polymorphic method.

- Andreas