OCaml polymorphism example other than template function?

I'm trying to figure out for myself what form of polymorphism the OCaml language has.

I have been provided with an example

let id x = x

      

Isn't this example equivalent to the C ++ template function

template<class A> A id(A x) { return x; }

      

If so, then my question is, are there any other forms of polymorphism in OCaml? This concept is called "universal algorithm" in the world of imperative languages, not "polymorphism".

+3


source to share


2 answers


There are basically three language features that are sometimes referred to as polymorphism:

  • Parametric polymorphism (ie "generics")
  • The politicism of subtypes is the ability of a subtype of a type to offer a more specific version of an operation than a supertype, i.e. the ability to override methods (and the runtime system's ability to call the correct implementation of a method based on the object's runtime type). In OO languages, this is often simply called "polymorphism".
  • The so-called ad-hoc polymorphism , that is, the ability to overload functions / methods.

As you already discovered, OCaml has parametric polymorphism. It also has subtype polymorphism. It has no ad-hoc polymorphism.



Since you asked for examples in your title, here is an example of subtype polymorphism in OCaml:

class c = object
    method m x = x+1
end

class d = object
    inherit c
    method m x = x+2
end

let main = 
    let o:c = new d in
    print_int (o#m 2)

      

This will print 4

.

+12


source


This kind of polymorphism is called general programming, but the theoretical concept behind it is called parametric polymorphism .

The two examples you gave do show parametric polymorphism, but OCaml is supported by a strong inferring setting, and the one provided by C ++ (this solution is more pragmatic and with a lot of caveats), so the real difference is that in C ++ the code is duplicated for every type you use in your code, while in OCaml it is resolved through type checking, verifying that implicit type variable substitution through unification exists.

Everything can be polymorphic in OCaml just because nothing is usually annotated with types, so in practice, if something can be used as an argument to any function, then it is implicitly allowed.

You can, for example, have type variables to define polymorphic methods:



let swap ((x : 'a), (y : 'b)) : 'b * 'a = (y, x)

      

so this will work regardless of the type 'a

o 'b

.

Another powerful polymorphic feature of OCaml is functors (which are not generic C ++ functors), but are modules parameterized by other modules. The concept sounds scarier than it is, but they do represent a higher order of polymorphic behavior for OCaml code.

+4


source







All Articles