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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With