Josh Stern (jstern / foshay.citilink.com) wrote:
> There is a real, non-trivial, example of template
> genericity being used to express mathematical ideas
> in the CGAL library:
> 
> http://www.cgal.org/Manual/doc_html/frameset/fsKernel.html
> http://www.cgal.org/Manual/doc_html/frameset/fsBasic.html
> 
> How to do such things in Ruby in full generality (efficiency
> aside)?  

To begin with, for the most basic use of generic types, no additional
effort is necessary--Array and Hash are obvious examples. For more
advanced schemes, it may be best to avoid the elaborate and
unnecessarily complicated maze of C++ templates and return to simpler
approaches. For instance, the instantion of a parametric type A[X] as
A[T], where X is a formal parameter and T a concrete type, can be seen
as specialization inheritance from A[X] with X = T. What we need for
this to work is to be able to work with types as first class
objects--something that C++ can't do, but Ruby can. Instantiating formal
parameters of generic types is basically constraining a family of
objects along one more dimensions. While I believe that somebody
mentioned earlier that genericity and inheritance are orthogonal
concepts, the opposite is true: generics introduce a classical is-a
relation, generally with full substitutivity (modulo the usual
covariance issues).

If the full machinery of inheritance is thus applied to a language, you
will get something like Beta's virtual patterns--where you cannot only
redefine functions along an inheritance hierarchy, but also types,
exceptions, etc. A similar approach was used by Meyer in the first
edition of Object Oriented Software Construction to avoid the
introduction of generic types. It has also been rediscovered as the
concept of "virtual types" for the purpose of introducing genericity in
Java.

A straightforward implementation would pass types, and whatever other
generic parameters you have, as arguments to 'new', to be stored in type
variables. Instantiating the formal paramaters would then be the
equivalent to performining currying on 'initialize'. Variants would be
having functions returning types, which can then be redefined, or
aliasing type names to constants. (And of course, when I'm referring to
types, just about any type of object can be substituted.)

The implementation of Z_n, for instance, should be a straightforward
exercise. The need of generics for a polynomial ring is not equally
obvious; we only need a type parameter as a simple case of a factory
pattern, and even this could be avoided if desired.

A lot of the problems that you have in many statically typed languages
just go away when you have types as first-class objects. It should also
be noted that just because something is part of C++ it should not
necessarily be added to another language; in fact, the converse is
generally true.

[...]

				Reimer Behrends