6 Polimorphism
This is probably the neatest thing in Gont. Structures, as
well as functions can be parameterized over types. For example to define
list of anything you write:
opt_struct <'a>list {
'a data;
<'a>list next;
}
'a is alpha. It is type variable, it stands for any type
(similarly 'b is beta, but I really don't know what 'foo is... :-)
Then you use it as:
<int>list l; // list of ints
<<int>list>list ll; // list of lists of ints
If you are familiar with C++ you can note `<<' that has to be written as
'< <' there. This is not the case in Gont. It is handled specially.
Functions can be written that operate on lists:
// Call passed function f on each element of the list l
// starting from head.
void iter(*('a) -> void f, <'a>list l)
{
while (l != null) {
f(l);
l = l.next;
}
}
// Call function f on each element of the list l,
// collect results as a list (of possibly different type)
// and return it.
<'b>list map(*('a) -> 'b f, <'a>list l)
{
<'b>list o = null;
while (l != null) {
o = {data = f(l.data), next = o};
l = l.next;
}
return o;
}
Later on you can use defined functions.
Suppose you have defined:
string int2string(int);
void print_string(string);
somewhere, then:
<int>list il = { data = 1, next = { data = 2, next = null }};
<string>list sl = map(int2string, il);
iter(print_string, sl);