Does OCaml have polymorphism?

Since OCaml has different operations for multiplying integers and doubles, how can this be object oriented? Doesn't that mean that OCaml has no polymorphism?

+4
source share
1 answer

Yes, OCaml has polymorphism. Here are a few reasons why arithmetic operations are not implemented as polymorphic methods:

  • Integer and double objects are not objects in OCaml, so they cannot have methods.
  • Operators in OCaml are functions, not methods. Of course, the language could be designed to use their methods instead, but then you could not define custom operators for anything that is not an object.
  • If you write a function of type f (x, y) = x + y , then the output type is int * int -> int . If you changed the language to make operator methods and ints objects, the intended type will be < + : 'a -> 'b; .. > * 'a -> 'b < + : 'a -> 'b; .. > * 'a -> 'b . Having such a complex type for such a simple function would probably be undesirable.
  • Paying the cost of a polymorphic dispatch every time an arithmetic operation is used will not work well.

Also note that in many major languages ​​that support operator overloading, operators are typically implemented as non-virtual (and therefore not polymorphic) methods or functions. Presumably due to the performance I mentioned above. The presence of polymorphic operators is rather unusual.

PS: In the context of functional languages, the term “polymorphism” is most often used to mean “parametric polymorphism” (what OO languages ​​are sometimes called “generics”), while in OO languages ​​it is most often used to mean “subtype of polymorphism”. This answer assumes that you used the last meaning of the word, since you explicitly indicated the object orientation, and since in this context the first meaning does not make sense.

+10
source

All Articles