20.03.2015 Views

The Objective Caml system release 3.06 - The Caml language - Inria

The Objective Caml system release 3.06 - The Caml language - Inria

The Objective Caml system release 3.06 - The Caml language - Inria

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

48<br />

int -><br />

object<br />

val mutable x : int<br />

method distance : #point0 -> int<br />

method get_offset : int<br />

method get_x : int<br />

method move : int -> unit<br />

end<br />

# let p = new distance_point 3 in<br />

# (p#distance (new point 8), p#distance (new colored_point 1 "blue"));;<br />

- : int * int = (5, 2)<br />

Note here the special syntax (#point0 as ’a) we have to use to quantify the extensible part<br />

of #point0. As for the variable binder, it can be omitted in class specifications. If you want<br />

polymorphism inside object field it must be quantified independently.<br />

# class multi_poly =<br />

# object<br />

# method m1 : ’a. (< n1 : ’b. ’b -> ’b; .. > as ’a) -> _ =<br />

# fun o -> o#n1 true, o#n1 "hello"<br />

# method m2 : ’a ’b. (< n2 : ’b -> bool; .. > as ’a) -> ’b -> _ =<br />

# fun o x -> o#n2 x<br />

# end;;<br />

class multi_poly :<br />

object<br />

method m1 : < n1 : ’a. ’a -> ’a; .. > -> bool * string<br />

method m2 : < n2 : ’b -> bool; .. > -> ’b -> bool<br />

end<br />

In method m1, o must be an object with at least a method n1, itself polymorphic. In method m2,<br />

the argument of n2 and x must have the same type, which is quantified at the same level as ’a.<br />

3.11 Using coercions<br />

Subtyping is never implicit. <strong>The</strong>re are, however, two ways to perform subtyping. <strong>The</strong> most general<br />

construction is fully explicit: both the domain and the codomain of the type coercion must be<br />

given.<br />

We have seen that points and colored points have incompatible types. For instance, they cannot<br />

be mixed in the same list. However, a colored point can be coerced to a point, hiding its color<br />

method:<br />

# let colored_point_to_point cp = (cp : colored_point :> point);;<br />

val colored_point_to_point : colored_point -> point = <br />

# let p = new point 3 and q = new colored_point 4 "blue";;<br />

val p : point = <br />

val q : colored_point = <br />

# let l = [p; (colored_point_to_point q)];;<br />

val l : point list = [; ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!