Module and Class in OCaml

ocaml

Solution

From a practical perspective dynamic lookup lets you have different objects with the same method without specifying to which class/module it belongs. It helps you when using inheritance.

For example, let's use two data structures: `SingleList` and `DoubleLinkedList`, which, both, inherit from `List` and have the method `pop`. Each class has its own implementation of the method (because of the 'override').

So, when you want to call it, the lookup of the method is done at runtime (a.k.a. dynamically) when you do a `list#pop`.

If you were using modules you would have to use `SingleList.pop list` or `DoubleLinkedList.pop list`.

EDIT: As @Majestic12 said, most of the time, OCaml users tend to use modules over classes. Using the second when they need inheritance or instances (check his answer).

I wanted to make the description practical as you seem new to OCaml.

Hope it can help you.

Problem

What are the differences between Module and Class in OCaml. From my searching, I found this: Both provide mechanisms for abstraction and encapsulation, for subtyping (by omitting methods in objects, and omitting fields in modules), and for inheritance (objects use inherit; modules use include). However, the two systems are not comparable. On the one hand, objects have an advantage: objects are first-class values, and modules are not—in other words, modules do not support dynamic lookup. On the other hand, modules have an advantage: modules can contain type definitions, and objects cannot. First, I don't understand what does "Modules do not support dynamic lookup" mean. From my part, abstraction and polymorphism do mean parent pointer can refer to a child instance. Is that the "dynamic lookup"? If not, what actually dynamic lookup means? In practical, when do we choose to use Module and when Class?

Original source