Since OCaml has different operations for multiplying integers and doubles, how it can be object-oriented? Doesn't this mean OCaml has no polymorphism?
Yes, OCaml has polymorphism. Here are some reasons why arithmetic operations aren't implemented as polymorphic methods:
- Integers and doubles aren't objects in OCaml, so they can't have methods.
- 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.
- If you write a function like
f (x, y) = x + y
the inferred type isint * 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. - 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.
© 2022 - 2024 — McMap. All rights reserved.