yjasrc
yjasrc

Reputation: 513

Module and Class in OCaml

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?

Upvotes: 15

Views: 2192

Answers (2)

snf
snf

Reputation: 3087

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.

Upvotes: 9

ChristopheLec
ChristopheLec

Reputation: 856

The main difference between Module and Class is that you don't instantiate a module.

A module is basically just a "drawer" where you can put types, functions, other modules, etc... It is just here to order your code. This drawer is however really powerful thanks to functors.

A class, on the other hand, exists to be instantiated. They contains variables and methods. You can create an object from a class, and each object contains its own variable and methods (as defined in the class).

In practice, using a module will be a good solution most of the time. A class can be useful when you need inheritance (widgets for example).

Upvotes: 13

Related Questions