Python and generic programming
Isaac To
iketo2 at netscape.net
Sat Nov 20 04:32:19 EST 2004
>>>>> "Terry" == Terry Reedy <tjreedy at udel.edu> writes:
Terry> Specialization goes in special methods -- the ones named
Terry> __xxx__ -- of which there are now 50-100. For each pair of
Terry> classes, at least one of the two must know how to do xxx on
Terry> the other. There is no way to get around the n square
Terry> problem, but Python pushes it into individual operations so
Terry> you only need one function that uses the operation. So
Terry> planning is required for a system of user-defined classed
Terry> such as multiple matrix implementations.
No, you don't quite understand what the OP is asking for. C++
templates are function or classes that is parameterized by some
arguments, the parameters can either be integer constants or type
names. So by writing a single template function you create (or
actually, you ask the compiler to create on-the-fly) many functions.
Upon using the parameterized function or class, the compiler will
choose/create the function or class for you. Specialization is a
mechanism that allows you to create a function that overrides the
implementation for some specific parameters. E.g., you can create a
"factorial" function as a template function:
template <int n>
int factorial() { return n * factorial<n-1>(); }
so that when asked, the compiler generates factorial<5>() as a
function which returns 5*factorial<4>(); factorial<4>() as a function
which returns 4*factorial<3>(), and so on. The terminal condition is
defined using a specialization:
template <>
int factorial<0>() { return 1; }
When the compiler wants to generate factorial<0>(), the more
specialized form is used, which stops the recursion. In this way you
create a compile-time computed factorial function. During compilation
the optimizer will turn it into a constant, so no computation is done
during run-time: factorial<10>() is in every conceivable way an
integer constant 3628800.
Another example is in the standard library: it defines a vector, which
is a resizable array for specific type (e.g., ints or strings)
normally. So a vector<int> will keep an int*, pointing to an array of
ints, used to hold the integers; and vector<string> will keep a
string*, pointing an array of strings. But if the specific type is
"bool", a bit-vector is created instead (i.e., an int* is used
instead, each int holds 32 values).
I don't see Python supporting generic program in the way C++ does, as
it does so little thing during "compile time" (which is just to
byte-compile the program). What I miss most is a mechanism that
allows programmers to define dispatching of functions based on types,
in a way that does not requires the programmer to specify how to do
dispatching (the compiler will figure it out by itself). I think
there's a PEP for that, though.
Regards,
Isaac.
More information about the Python-list
mailing list