Parametric Polymorphism - mfichman/jogo GitHub Wiki
Basics
Functions and classes can use a feature called parametric polymorphism, which allows them to be written independent of one or more types. Also known as 'generics' and 'templates,' this feature allows the programmer to write an algorithm once that works for many types.
List[:a] < Interface {
get(index Int) :a
set(intex Int, val :a)
}
The example above defines a list that can contain any type of element. Notice the brackets in List[:a]
. When a List
is created, the :a
can be replaced by any type.
list = List[Int]
The code above creates a new list, with Int
replacing :a
in the definition of List[:a]
.
Operation binding
To make generics more powerful, Jogo allows operations to be bound to polymorphic parameters, like :a
.
min(first :a, second :a) :a {
if first.less(second) {
ret first
} else {
ret second
}
}
The min
function here causes the operation less()
to be bound to the type :a
. That means that the values passed to min must respond to the method less()
.