[Haskell-cafe] I miss OO

On Wed, Nov 25, 2009 at 2:08 PM, Erik de Castro Lopo
<mle+hs at mega-nerd.com> wrote:
> Michael Mossey wrote:
>>> I'm fairly new to Haskell, and starting to write some big projects.
>> Previously I used OO exclusively, mostly Python. I really miss the
>> "namespace" capabilities... a class can have a lot of generic method names
>> which may be identical for several different classes because there is no
>> ambiguity.
>>>> In my musical application, many "objects" (or in Haskell, data) have a time
>> associated with them. In Python I would have an accessor function called
>> "time" in every class.
>> This is what Type Classes in Haskell are for. See:
>>http://www.haskell.org/tutorial/classes.html
I feel like this should be qualified. Type classes are not for name
punning ; you wouldn't use a type class for the method bark on types
Tree and Dog. But if you have a well-defined *structure* that many
types follow, then a type class is how you capture that. It sounds
like you do have this structure in your example.
Further, with typeclasses, you can write methods that are generic over
any type with that structure. So:
class Temporal a where
time :: a -> Time
temporalOrder :: Temporal a => [a] -> [a]
temporalOrder = sortBy (comparing time)
The ability to do this indicates why using them for punning is a bad idea.
Luke