Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modular programming in ocaml

I found something which I don't really understand while working on an ocaml project.

Suppose I'm using both the Array and List modules of OCaml standard library. They both implement the function length but have different types. In the List module, this is its type:

length: a' list -> int

And in the Array module, it has the type:

length: a' array -> int

But then I wanted you use both modules in the same module I was implementing, via the open keyword:

open List
open Array

When I tried to use the length function on a list, I had a type error during compilation.
Since OCaml is a strong statically typed language, I'm wondering why the compiler didn't know I wanted the length function of the list module since I declared I was using both.

like image 200
Joseph Elcid Avatar asked Jul 31 '12 08:07

Joseph Elcid


People also ask

What are modules OCaml?

ocaml modules allow to package together data structures definitions and functions operating on them. This allow to reduce code size and name confusion, as any identifier can appear in different modules, with different meanings, without any interference.

Is OCaml functional or object oriented?

Objects and classes. OCaml is an object-oriented, imperative, functional programming language :-) It mixes all these paradigms and lets you use the most appropriate (or most familiar) programming paradigm for the task at hand.

What are the features of modular programming?

Modular programming allows many programmers to collaborate on the same application. The code is stored across multiple files. Code is short, simple and easy to understand. Errors can easily be identified, as they are localized to a subroutine or function.

What programming paradigm is Modula?

Modular programming paradigm:- The modular programming paradigm is subdividing the program into separate small programs called modules. Each module is designed to perform specific functions. Modules make the actual program shorter, hence easier to read and understand.


1 Answers

OCaml does not choose one function or another based on their types.

When you write

open Array

the functions of module Array are masking the ones of module List with the same name. When you later call the function length, OCaml looks for a function named length, finds Array.length, and complains that this function does not have a compatible type.

The usual way is to call List.length (instead of just length) if that is the function you need.


More generaly, OCaml does not have name overloading (i.e. having two functions or operators with the same name but distinct argument types), in particular because this would make type inference much harder.

like image 132
jrouquie Avatar answered Nov 15 '22 09:11

jrouquie