(* A simple example of type inference *)
# let add5 x = x + 5;;
val add5 : int -> int = <fun>
# let add5point0 x = x +. 5.0;;
val add5point0 : float -> float = <fun>
(* A more complex example of type inference *)
# let l1 = ["way"; "down"; "upon"; "the"; "swanee"; "river"];;
val l1 : string list = ["way"; "down"; "upon"; "the"; "swanee"; "river"]
# let l2 = [5; 4; 3; 2; 1];;
val l2 : int list = [5; 4; 3; 2; 1]
#let rec sort lst =
match lst with
[] -> []
| head :: tail -> insert head (sort tail)
and insert elt lst =
match lst with
[] -> [elt]
| head :: tail -> if elt <= head then
elt :: lst else head :: insert elt tail;;
val sort : 'a list -> 'a list = <fun>
val insert : 'a -> 'a list -> 'a list = <fun>
# sort l1;;
- : string list = ["down"; "river"; "swanee"; "the"; "upon"; "way"]
# sort l2;;
- : int list = [1; 2; 3; 4; 5]
|
|
Objective Caml has type inference. The programmer need not give any type
information within the program. This inference is carried out jointly with
verification, during program compilation. Type inference allows for greater
programming freedom. |