Benefits of OCaml

Parametric polymorphism

When type inference determines than an expression is valid for any type it is automatically made polymorphic. In OCaml, the polymorphic types in type expressions are denoted 'a, 'b, 'c and so on. For example, the following function reverses the order of the elements in a 2-tuple and can be applied to 2-tuples of values of any type:

# let rev2 (x, y) = (y, x);;
val rev2 : 'a * 'b -> 'b * 'a = <fun>
# rev2 (1, 2);;
- : int * int = (2, 1)
# rev2 (1, "hello");;
- : string * int = ("hello", 1)

Parametric polymorphism is an extremely useful feature. In particular, it allows generic containers to be manipulated easy.

Built-in polymorphic functions

OCaml provides built-in comparison and hashing functions. These are very useful as they can be applied to arbitrarily complicated data structures. However, they are based upon structural comparison, which is not always equivalent to semantic comparison. For example, when representing sets of values as balanced binary trees, structurally different trees can represent the same set. So the polymorphic comparison functions should not be applied to non-trivial data structures.

Comparison

There are several built-in comparison functions that can be applied to pairs of values of any type. These functions are <, >, <=, >= and compare.

The compare function provides a total ordering. For example:

# compare 2 3;;
- : int = -1
# compare 3 3;;
- : int = 0
# compare 4 3;;
- : int = 1

As these comparison functions are polymorphic, they can be applied to values of any type. For example, to compare lists of integers:

# [1; 2; 3] < [2; 3; 4];;
- : bool = true

Polymorphic comparison functions provide a simple way to compare arbitrary data structures.

Hashing

OCaml also provides a polymorphic hash function and a generic hash table implementation.

For example, the following code sets up a hash table mapping lists of integers onto strings:

# let m = Hashtbl.create 1;;
val m : ('_a, '_b) Hashtbl.t = 
# Hashtbl.add m [1; 2; 3] "abc";
  Hashtbl.add m [1; 2; 4] "abd";
  Hashtbl.add m [2; 3; 4] "bcd";;
- : unit = ()
# Hashtbl.find m [1; 2; 4];;
- : string = "abd"

An efficient built-in hash table implementation and polymorphic hashing function make it very easy to use this important data structure in OCaml programs.