Benefits of OCaml

Objects

OCaml provides Object Oriented Programming (OOP). However, the approach to OOP taken by OCaml is unlike that used by C++ and Java. Specifically, OCaml also provides classes but adds the concept of immediate objects, regards objects as equivalent (subtypes) if they implement the same implicit sub-interface (i.e. they provide the same members) and entwines the object system with the static type system so that objects can exploit other features of OCaml (e.g. parametric polymorphism, higher-order member functions).

For example, the following OCaml code implements the pedagogical class hierarchy with an abstract base class (ABC) shape and derived classes triangle and square:

# class virtual shape = object
    method virtual print : unit
  end

  class triangle = object
    inherit shape
    method print = print_endline "A triangle"
  end

  class square = object
    inherit shape
    method print = print_endline "A square"
  end;;
class virtual shape : object method virtual print : unit end
class triangle : object method print : unit end
class square : object method print : unit end

# let my_square = new square;;
val my_square : square = <obj>

# my_square#print;;
A square
- : unit = ()

Note that variant types are often preferable to objects, to the extent that OCaml's objects are used far less than objects in C++ and particularly Java (where the programmer is forced to use OOP). For example, the shape class hierarchy may be expressed much more clearly and simply using a variant type:

# type shape = Triangle | Square;;
type shape = Triangle | Square

# let print = function
    | Triangle -> print_endline "A triangle"
    | Square -> print_endline "A square";;
print : shape -> unit = <fun>

# let my_square = Square;;

# print my_square;;
A square
- : unit = ()

OCaml's object system provides the only way to execute a function after a value becomes unreachable. Objects can then be used to manage external resources, automatically deallocating them after they are no longer used by the program.

In very large programs, OOP can be used to help manage complexity.