Some examples for type inference algorithm


let add5 x = 5 + x;;

let add_pair x = fst x + snd x;;

let switch_pair x = (snd x, fst x);;

(* what is this?? *)
let f x = ((fst x) + 1) :: snd x;;

(* and this?? *)
let f x = (fst x + snd x) :: x;;

(*recursive functions*)

let rec count x = match x with
 [] -> 0
|y::ys -> 1 + count ys;;

let rec remove x y = match y with
 [] -> []
|z::zs -> if z = x then remove x zs else z::remove x zs;;

(* to test remove and count on functions*)
let f x = x;;

(* count works on lists of any type *)
count [3; 6; 8];;
count [f; f];;

(* remove works on non-function types *)
remove 2 [3; 2; 4; 2];;

(* this breaks at run-time since functions are not comparable: *)
remove f [f; f];;

(* this works, proving that the error happens at function comparison. *) 
(* no function comparison -- no error: *)
remove f [];;

CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.