- Courses
- 💻Programming Languages
- 🐫OCaml (WIP)
- Object-Oriented Programming
- Exercise: Objects vs Modules
On this page
OCaml OO vs Functor: Shape Library Exercise
Published on September 19, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
This guided exercise implements a shape library twice: once using OCaml's object system and once using modules and functors. The two implementations expose the same operations—computing the area and perimeter of circles, rectangles, and triangles, and iterating over heterogeneous collections of shapes. After building both, you will add a new shape type to each, add a new operation to each, and compare the results. The goal is to experience the expression problem directly rather than reading about it abstractly.
The Component: A Shape Library
The component must satisfy these requirements:
- Represent three shape types: circle, rectangle, and triangle.
- Compute the area of any shape.
- Compute the perimeter of any shape.
- Build a heterogeneous collection containing shapes of different types.
- Compute the total area and total perimeter of a collection.
The circle has a radius. The rectangle has a width and a height. The triangle has three side lengths and uses Heron's formula for its area.
Part 1: The Object-Oriented Implementation
The object-oriented design uses an abstract base class that declares the two operations as virtual methods. Each concrete shape class inherits from the base class and implements the methods.
Step 1.1: Define the Abstract Shape Class
class virtual shape =
object
method virtual area : float
method virtual perimeter : float
end
The shape class declares two virtual methods: area and perimeter, both returning float. Because the class contains virtual methods, it is declared virtual and cannot be instantiated directly. It serves only as a template for concrete subclasses.
Step 1.2: Define the Circle Class
class circle radius =
object
inherit shape
method area = Float.pi *. radius *. radius
method perimeter = 2.0 *. Float.pi *. radius
end
The circle class inherits from shape and implements both virtual methods. The radius parameter is captured by the methods through closure. The class is concrete because all virtual methods are implemented.
Step 1.3: Define the Rectangle Class
class rectangle width height =
object
inherit shape
method area = width *. height
method perimeter = 2.0 *. (width +. height)
end
The rectangle class follows the same pattern, implementing area as width times height and perimeter as twice the sum of width and height.
Step 1.4: Define the Triangle Class
class triangle a b c =
object
inherit shape
method perimeter = a +. b +. c
method area =
let s = (a +. b +. c) /. 2.0 in
sqrt (s *. (s -. a) *. (s -. b) *. (s -. c))
end
The triangle class implements perimeter as the sum of the three sides and area using Heron's formula. The semi-perimeter s is computed inside the area method.
Step 1.5: Build a Heterogeneous Collection
Because object types are structural, a list of shapes can contain objects from different classes as long as each is coerced to the shape type. The coercion operator :> performs this conversion.
let shapes : shape list =
[ (new circle 1.0 :> shape);
(new rectangle 2.0 3.0 :> shape);
(new triangle 3.0 4.0 5.0 :> shape) ]
Each new ... expression creates an object. The coercion (expr :> shape) hides the concrete class and produces a value of type shape. The list shapes has type shape list.
Step 1.6: Compute Totals
With the collection built, computing total area and perimeter uses List.fold_left and method invocation.
let total_area (shapes : shape list) =
List.fold_left (fun acc s -> acc +. s#area) 0.0 shapes
let total_perimeter (shapes : shape list) =
List.fold_left (fun acc s -> acc +. s#perimeter) 0.0 shapes
let () =
Printf.printf "Total area: %.4f\n" (total_area shapes);
Printf.printf "Total perimeter: %.4f\n" (total_perimeter shapes)
The lambda fun acc s -> acc +. s#area calls the area method on each shape. Method dispatch is resolved at runtime based on the actual class of the object.
Part 2: The Functor-Based Implementation
The functor-based design uses a variant type for the shape and a module signature for the operations. The variant type is defined once, and the operations are functions that pattern-match on the variant constructors.
Step 2.1: Define the Shape Variant Type
type shape =
| Circle of float
| Rectangle of float * float
| Triangle of float * float * float
The shape type is a regular variant with three constructors. Each constructor carries the parameters needed to describe the shape. The type is closed; no new constructors can be added outside this definition.
Step 2.2: Define the Shape Signature
module type SHAPE = sig
type t
val area : t -> float
val perimeter : t -> float
end
The SHAPE signature declares an abstract type t and two functions. It does not specify what t is, which allows different implementations to use different representations.
Step 2.3: Implement the Shape Module
module Shape : SHAPE with type t = shape = struct
type t = shape
let area = function
| Circle r -> Float.pi *. r *. r
| Rectangle (w, h) -> w *. h
| Triangle (a, b, c) ->
let s = (a +. b +. c) /. 2.0 in
sqrt (s *. (s -. a) *. (s -. b) *. (s -. c))
let perimeter = function
| Circle r -> 2.0 *. Float.pi *. r
| Rectangle (w, h) -> 2.0 *. (w +. h)
| Triangle (a, b, c) -> a +. b +. c
end
The Shape module matches SHAPE with the additional equation type t = shape. This equation exposes the variant type so that callers can construct shapes. The area and perimeter functions pattern-match on the three constructors.
Step 2.4: Build a Heterogeneous Collection
The collection is a shape list, built directly from the variant constructors.
let shapes : Shape.t list =
[ Shape.Circle 1.0;
Shape.Rectangle (2.0, 3.0);
Shape.Triangle (3.0, 4.0, 5.0) ]
No coercion is needed because all three values have the same variant type.
Step 2.5: Compute Totals
let total_area (shapes : Shape.t list) =
List.fold_left (fun acc s -> acc +. Shape.area s) 0.0 shapes
let total_perimeter (shapes : Shape.t list) =
List.fold_left (fun acc s -> acc +. Shape.perimeter s) 0.0 shapes
let () =
Printf.printf "Total area: %.4f\n" (total_area shapes);
Printf.printf "Total perimeter: %.4f\n" (total_perimeter shapes)
The lambda calls Shape.area or Shape.perimeter directly. There is no method dispatch; the function is bound at compile time.
Part 3: Add a New Shape Type
Now extend both implementations with a new shape: a square. The square has a single side length, and its area is side squared, its perimeter four times the side.
Object-Oriented Version
Adding a square requires defining a new class. No existing code changes.
class square side =
object
inherit shape
method area = side *. side
method perimeter = 4.0 *. side
end
The square class inherits from shape and implements both methods. It can be added to the collection with a coercion:
let shapes_with_square =
(new square 2.0 :> shape) :: shapes
The original shapes list is unchanged. The total_area and total_perimeter functions work without modification because they only use the shape interface.
Functor-Based Version
Adding a square requires modifying the variant type and every function that matches on it.
type shape =
| Circle of float
| Rectangle of float * float
| Triangle of float * float * float
| Square of float
The area and perimeter functions in the Shape module must both be updated to handle the new constructor:
let area = function
| Circle r -> Float.pi *. r *. r
| Rectangle (w, h) -> w *. h
| Triangle (a, b, c) ->
let s = (a +. b +. c) /. 2.0 in
sqrt (s *. (s -. a) *. (s -. b) *. (s -. c))
| Square s -> s *. s
let perimeter = function
| Circle r -> 2.0 *. Float.pi *. r
| Rectangle (w, h) -> 2.0 *. (w +. h)
| Triangle (a, b, c) -> a +. b +. c
| Square s -> 4.0 *. s
The compiler warns if either function does not handle the new constructor. Every function that pattern-matches on shape must be updated. In this small example, only two functions need changes. In a larger codebase with dozens of operations on shapes, every one of them would need to be revisited.
Part 4: Add a New Operation
Now add a new operation: computing the bounding box area of a shape. For a circle, the bounding box is a square with side equal to the diameter, so its area is ((2r)^2 = 4r^2). For a rectangle, the bounding box area equals the rectangle's area. For a triangle, computing the exact bounding box area is complex; for this exercise, approximate it as the area of the triangle multiplied by two.
Object-Oriented Version
Adding a bounding box operation requires modifying the abstract shape class and every concrete subclass.
class virtual shape =
object
method virtual area : float
method virtual perimeter : float
method virtual bounding_box_area : float
end
Every subclass must now implement bounding_box_area:
class circle radius =
object
inherit shape
method area = Float.pi *. radius *. radius
method perimeter = 2.0 *. Float.pi *. radius
method bounding_box_area = 4.0 *. radius *. radius
end
class rectangle width height =
object
inherit shape
method area = width *. height
method perimeter = 2.0 *. (width +. height)
method bounding_box_area = width *. height
end
class triangle a b c =
object
inherit shape
method perimeter = a +. b +. c
method area =
let s = (a +. b +. c) /. 2.0 in
sqrt (s *. (s -. a) *. (s -. b) *. (s -. c))
method bounding_box_area = 2.0 *. (a +. b +. c)
end
Every class must be edited. If a class is defined in a separate file or a separate library, that file or library must be recompiled. The square class added earlier must also be updated.
Functor-Based Version
Adding a bounding box operation requires defining one new function. No existing code changes.
let bounding_box_area = function
| Circle r -> 4.0 *. r *. r
| Rectangle (w, h) -> w *. h
| Triangle (a, b, c) -> 2.0 *. (a +. b +. c)
| Square s -> s *. s
The function is defined in the Shape module. All existing functions—area, perimeter—remain unchanged. Callers that need the new operation simply call it. Callers that do not need it are unaffected.
Part 5: Performance Comparison
Method dispatch in the object-oriented version uses a dispatch table lookup. The functor-based version uses direct function calls that the compiler can inline. To measure the difference, create a list of one million shapes and sum their areas one thousand times.
let big_list =
List.init 1_000_000 (fun i ->
if i mod 3 = 0 then Shape.Circle 1.0
else if i mod 3 = 1 then Shape.Rectangle (2.0, 3.0)
else Shape.Triangle (3.0, 4.0, 5.0))
let () =
let start = Unix.gettimeofday () in
for _ = 1 to 1000 do
ignore (total_area big_list)
done;
let elapsed = Unix.gettimeofday () -. start in
Printf.printf "Functor-based: %.4f seconds\n" elapsed
Run the equivalent benchmark with the object-oriented collection. The object-oriented version will typically be two to three times slower because each s#area involves a dynamic lookup. The functor-based version calls Shape.area s, which the compiler can optimize.
The exact ratio depends on the compiler backend. Native compilation reduces the absolute cost of both, but the relative gap remains. For applications where this loop is the bottleneck, the functor-based version is measurably faster.
Part 6: Summary of the Comparison
DimensionObject-OrientedFunctor-BasedAdd a new shape typeDefine a new class; no existing code changesModify the variant type and every function that matches on itAdd a new operationModify the abstract class and every subclassDefine one new function; no existing code changesHeterogeneous collectionCoerce each object to the base typeUse the variant type directlyType safetyStructural subtyping; coercions requiredVariant type; no coercionsPerformanceDynamic dispatch; 2–3× slowerStatic dispatch; inlinableCompilation couplingNew shapes are independentNew operations are independent
The object-oriented version is open for new shapes and closed for new operations. The functor-based version is open for new operations and closed for new shapes. Neither is universally superior. The choice depends on which kind of extension the problem requires more often.
For a shape library where new shapes are added frequently and new operations are rare, objects are the better fit. For a shape library where new operations are added frequently and new shapes are rare, the functor-based design is the better fit. Recognizing this tradeoff in advance prevents the costly restructuring that occurs when the wrong model is chosen for the wrong kind of extension.
Key Takeaways
Implementing a shape library twice reveals the dual nature of OCaml's abstraction mechanisms. Objects make it easy to add new shape types by defining new classes, but adding new operations requires modifying every class in the hierarchy. Functors and variants make it easy to add new operations by defining new functions, but adding new shape types requires modifying the variant and every function that matches on it. Performance favors the functor-based approach because direct function calls can be inlined while method dispatch cannot. The right choice for a given component depends on whether the component is expected to grow by adding new implementations or by adding new operations.
Frequently Asked Questions
What is the purpose of implementing a component both ways?
Implementing the same component with objects and with functors makes the expression problem concrete. The reader experiences directly which kind of extension is easy in each model and which is costly, building the judgment to choose the right tool for a given problem.
Which implementation is better for the shape library?
Neither is universally better. The object-oriented version is better when new shape types are added frequently. The functor-based version is better when new operations are added frequently. The right choice depends on the expected pattern of change.
Why is the object-oriented version slower?
Method invocation uses dynamic dispatch, which involves looking up the method in a dispatch table. The functor-based version uses direct function calls that the compiler can inline. The indirection in method dispatch is the source of the performance difference.
Can I mix objects and functors in the same program?
Yes. OCaml allows both to coexist. A common pattern is to use functors to produce objects of a particular type, combining the type abstraction of modules with the late binding and subtyping of objects where they are needed.
What happens if I forget to update a pattern match in the functor-based version?
The compiler issues a warning about a non-exhaustive match. If warnings are treated as errors during development, the build fails, forcing you to handle the new constructor. This is one of the safety advantages of the functor-based approach.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Objects vs Modules & Functors
Next
🪟PowerShell
-
The Component: A Shape Library
-
Part 1: The Object-Oriented Implementation
- Step 1.1: Define the Abstract Shape Class
- Step 1.2: Define the Circle Class
- Step 1.3: Define the Rectangle Class
- Step 1.4: Define the Triangle Class
- Step 1.5: Build a Heterogeneous Collection
- Step 1.6: Compute Totals
-
Part 2: The Functor-Based Implementation
- Step 2.1: Define the Shape Variant Type
- Step 2.2: Define the Shape Signature
- Step 2.3: Implement the Shape Module
- Step 2.4: Build a Heterogeneous Collection
- Step 2.5: Compute Totals
-
Part 3: Add a New Shape Type
- Object-Oriented Version
- Functor-Based Version
-
Part 4: Add a New Operation
- Object-Oriented Version
- Functor-Based Version
-
Part 5: Performance Comparison
-
Part 6: Summary of the Comparison
-
Key Takeaways
-
Frequently Asked Questions
