Reputation: 877
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.
Upvotes: 5
Views: 377
Reputation: 4405
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.
Upvotes: 8