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.

44<br />

# end;;<br />

class [’a] ref_succ :<br />

’a -><br />

object<br />

constraint ’a = int<br />

val mutable x : int<br />

method get : int<br />

method set : int -> unit<br />

end<br />

Let us consider a more complex example: define a circle, whose center may be any kind of point. We<br />

put an additional type constraint in method move, since no free variables must remain unaccounted<br />

for by the class type parameters.<br />

# class [’a] circle (c : ’a) =<br />

# object<br />

# val mutable center = c<br />

# method center = center<br />

# method set_center c = center unit)<br />

# end;;<br />

class [’a] circle :<br />

’a -><br />

object<br />

constraint ’a = < move : int -> unit; .. ><br />

val mutable center : ’a<br />

method center : ’a<br />

method move : int -> unit<br />

method set_center : ’a -> unit<br />

end<br />

An alternate definition of circle, using a constraint clause in the class definition, is shown below.<br />

<strong>The</strong> type #point used below in the constraint clause is an abbreviation produced by the definition<br />

of class point. This abbreviation unifies with the type of any object belonging to a subclass of class<br />

point. It actually expands to < get_x : int; move : int -> unit; .. >. This leads to the<br />

following alternate definition of circle, which has slightly stronger constraints on its argument, as<br />

we now expect center to have a method get_x.<br />

# class [’a] circle (c : ’a) =<br />

# object<br />

# constraint ’a = #point<br />

# val mutable center = c<br />

# method center = center<br />

# method set_center c = center <br />

object

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

Saved successfully!

Ooh no, something went wrong!