[Haskell-cafe] Re: type class question

Jules Bean jules at jellybean.co.uk
Mon Dec 10 07:55:11 EST 2007

Peter Padawitz wrote:
> Jules Bean wrote:
>> Peter Padawitz wrote:
>>> What is so bad about making compFoo part of the class? It reduces the 
>>> code (constraints can be avoided) and reflects the close connection 
>>> between  a signature Sig (implemented by the class) and the 
>>> evaluation (compFoo) of Sig-terms in Sig-algebras.
>> making it part of the class allows instances to override the 
>> implementation.
>> Which in this case is a strange thing to do.
> Sure, but this can only happen because Haskell does not check whether 
> the instances satisfy the equations in the class. The type class concept 
> would be "cleaner" if all methods (partially or totally) defined by 
> equations within the class were not allowed to be instantiated!

I don't see why!

In the class

class Foo a where
   f :: a -> Int
   g :: b -> Integer
   g = fromIntegral . f

The equations within the class are defaults, not equations. The equation 
for 'g' is a default, not a rule.

If you want equations, you do it outside the class. I have written that 
class wrongly, I should actually write g = fromIntegral . f as a 
function outside the class, thus guaranteeing the implementation and 
stopping people breaking that invariant.

The purpose of methods with defaults is to allow the possibility that 
there is an obvious natural way to implement one function in terms of 
others, but there might be more efficient ways.

For example, the Foldable class should (but doesn't) have a member 
length. This could be defaulted to length . toList, but have a more 
efficient implementation in Sequence, which stores its own length anyway.

Or maybe we are at cross-purposes.


More information about the Haskell-Cafe mailing list