OO in Python? ^^

Donn Cave donn at u.washington.edu
Wed Dec 14 15:07:01 EST 2005


In article <1134557152.748134.255180 at g47g2000cwa.googlegroups.com>,
 bonono at gmail.com wrote:
> Magnus Lycka wrote:
> > Assume that you didn't use Python, but rather something with
> > static typing. How could you make a module such as my_module.py,
> > which is capable of working with any type that supports some
> > standard copy functionality and the +-operator?
> 
> The following is a very short Haskell function I defined which I hope
> can give you some idea.
...

> *MyList> :type breakKeyword
> breakKeyword :: (Eq a) => [a] -> [a] -> ([a], [a])
> 
> What it means is that breakKeyword can take any list of object type "a"
> so long it belongs to the class Eq. It can be char, number or whatever
> so long it is an instance of Eq.
> 
> All that is needed for my custom data type(whatever it is) is that it
> must implment the compare function that "elem" would use to compare if
> a given object is in the list of token.
> 
> *MyList> :type elem
> elem :: (Eq a) => a -> [a] -> Bool

Moreover, 1) this compare implementation is (as I understand it)
made available via runtime information, so a typeclass instance
may be implemented after the function that encounters it was compiled,
and 2) implementation often requires no more than "deriving Eq"
after the data type declaration -- assuming the data type is
composed of other types of data, you can infer the functional
composition of a typeclass instance.

The sum function in my_module.py was, in a very approximate sense,
like the standard "foldr" function.  Of course foldr doesn't need to
copy, nor does it use any += operator.   foldr is generic to any
function of type (a -> a -> b) (i.e., takes two parameters of one
type and returns a value of another type.)  Lists don't support
a (+) operation (numeric only), but they support (++) concatenation
and (:) composition.  foldr also takes an initial parameter of type b.

so,
      foldr (:) "" ['a', 'b', 'c']
      foldr (++) [] [[1, 2, 3], [4, 4, 4]]

Really, this kind of abstraction of data types is not only well
supported in Haskell, it can be almost a curse, at least for
someone like myself who has fairly superficial experience with
this kind of programming.  After all the functions have been
zealously scrubbed clean of any trace of concrete data types and
rendered maximally abstract, they can be a little hard to understand.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list