Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does OCaml have polymorphism?

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

like image 770
Suzan Cioc Avatar asked Jan 20 '13 12:01

Suzan Cioc


1 Answers

Yes, OCaml has polymorphism. Here are some reasons why arithmetic operations aren't implemented as polymorphic methods:

  1. Integers and doubles aren't objects in OCaml, so they can't have methods.
  2. Operators in OCaml are functions, not methods. Of course the language could have been designed to make them methods instead, but then you could not define custom operators for anything that isn't an object.
  3. If you write a function like f (x, y) = x + y the inferred type is int * int -> int. If you changed the language to make operators methods and ints objects, the inferred type would be < + : 'a -> 'b; .. > * 'a -> 'b. Having such a complicated type for such a simple function would probably not be desirable.
  4. Paying the cost of polymorphic dispatch every time an arithmetic operation is used would be bad for performance.

Also note that in many mainstream languages that support operator overloading, operators tend to be implemented as non-virtual (and thus non-polymorphic) methods or functions as well. Presumably for the performance reason I mentioned above. Having polymorphic operators is rather uncommon.

PS: In the context of functional languages the term "polymorphism" is most often used to refer to "parametric polymorphism" (what OO languages sometimes call "generics"), while in OO languages it is most often used to refer to "subtype polymorphism". This answer assumes that you were using the latter meaning of the word since you explicitly mentioned object orientation and since the former meaning doesn't really make sense in this context.

like image 134
sepp2k Avatar answered Sep 27 '22 20:09

sepp2k