[Python-3000] Breakthrough in thinking about ABCs (PEPs 3119 and 3141)
Jason Orendorff
jason.orendorff at gmail.com
Tue May 1 06:32:04 CEST 2007
On 4/30/07, Guido van Rossum <guido at python.org> wrote:
> The correct
> approach is for TotallyOrdered to be a metaclass (is this the
> typeclass thing in Haskell?).
Mmmm. Typeclasses don't *feel* like metaclasses. Haskell types
aren't objects.
A typeclass is like an interface, but more expressive. Only an
example has any hope of delivering the "aha!" here:
-- This defines a typeclass called "Set e".
-- "e" and "s" here are type variables.
class Set e s where
-- here are a few that behave like OO methods...
size :: s -> Int -- (size set) returns an Int
contains :: s -> e -> Bool -- (contains set element) returns Bool
-- here are some where the two arguments have to be of the same type
union :: s -> s -> s
intersection :: s -> s -> s
-- here's a constructor!
fromList :: [e] -> s
-- and here's a constant... with a default implementation!
emptySet :: s
emptySet = fromList []
Suppose someone has written a super-fast data structure for
collections of ints. If I wanted to "register" that type as a Set, I
would write:
instance Set Int FastIntSet where
-- the implementation goes in here
size self = ...implement this using FastIntSet magic...
More complex relationships among types are surprisingly easy to
express. See if you can puzzle these out:
instance Hashable e => Set e (HashSet e) where ...
instance Cmp e => Set e (TreeSet e) where ...
class PartialOrd t where
(<=*) :: t -> t -> Bool
instance (Set s, Eq s) => PartialOrd s where
(a <=* b) = (intersection a b == a)
See? It's nice. But, eh, this is what typeful languages do
all day; they'd better be good at it. :)
-j
(Right now on a Haskell mailing list somewhere, a mirror image of me
is trying to explain what's so cool about zipfile. Python wins. ;)
More information about the Python-3000
mailing list