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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

46<br />

# let l = new intlist [1; 2; 3];;<br />

val l : ’_a intlist = <br />

# l#fold (fun x y -> x+y) 0;;<br />

- : int = 6<br />

# l;;<br />

- : int intlist = <br />

# l#fold (fun s x -> s ^ string_of_int x ^ " ") "";;<br />

This expression has type int but is here used with type string<br />

Our iterator works, as shows its first use for summation. However, since objects themselves are not<br />

polymorphic (only their constructors are), using the fold method fixes its type for this individual<br />

object. Our next attempt to use it as a string iterator fails.<br />

<strong>The</strong> problem here is that quantification was wrongly located: this is not the class we want to<br />

be polymorphic, but the fold method. This can be achieved by giving an explicitly polymorphic<br />

type in the method definition.<br />

# class intlist (l : int list) =<br />

# object<br />

# method empty = (l = [])<br />

# method fold : ’a. (’a -> int -> ’a) -> ’a -> ’a =<br />

# fun f accu -> List.fold_left f accu l<br />

# end;;<br />

class intlist :<br />

int list -><br />

object method empty : bool method fold : (’a -> int -> ’a) -> ’a -> ’a end<br />

# let l = new intlist [1; 2; 3];;<br />

val l : intlist = <br />

# l#fold (fun x y -> x+y) 0;;<br />

- : int = 6<br />

# l#fold (fun s x -> s ^ string_of_int x ^ " ") "";;<br />

- : string = "1 2 3 "<br />

As you can see in the class type shown by the compiler, while polymorphic method types must be<br />

fully explicit in class definitions (appearing immediately after the method name), they can be left<br />

implicit in class descriptions.<br />

However, the type can be completely omitted in the class definition if it is already known,<br />

through inheritance or type constraints on self. Here is an example of method overriding.<br />

# class intlist_rev l =<br />

# object<br />

# inherit intlist l<br />

# method fold f accu = List.fold_left f accu (List.rev l)<br />

# end;;<br />

<strong>The</strong> following idiom separates description and definition.

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

Saved successfully!

Ooh no, something went wrong!