immediate objects

http://caml.inria.fr/pub/docs/manual-ocaml/manual005.html#ss:immediate-objects

OCaml 3.08から入った、オブジェクト式。

# let x = object
            method f x = x+1
          end;;
val x : < f : int -> int > = <obj>
# x#f 3;;
- : int = 4

とかできる。

先日気づいたのだが、

# let x = object
            method id x = x
          end;;
val x : < id : 'a -> 'a > = <obj>
# begin
    x#id 1;
    x#id "foo"
  end;;
Warning: this expression should have type unit.
- : string = "foo"

とかできてしまう。Polymorphic Methodは型推論できないはずなのだが。

現に、クラスにすると

# class c = object
              method id x = x
            end;;
Some type variables are unbound in this type:
  class c : object method id : 'a -> 'a end
The method id has type 'a -> 'a where 'a is unbound

はエラーになってしまう。

とはいえ、object式の中身もpolymorphic methodに型推論されているわけではない。

ちなみにPolymorphic Methodの型は

# object
    method f : 'a. 'a -> 'a = fun x -> x   (* 明示的な型指定 *)
  end;;
- : < f : 'a. 'a -> 'a > = <obj>

となる。