[Haskell-beginners] Real world example of Typeclasses > Interfaces

Alec Benzer alecbenzer at gmail.com
Sat Sep 4 14:42:50 EDT 2010


On Sat, Sep 4, 2010 at 1:54 PM, Brent Yorgey <byorgey at seas.upenn.edu> wrote:
> On Sat, Sep 04, 2010 at 01:04:43PM -0400, Alec Benzer wrote:
>> On Sat, Sep 4, 2010 at 12:29 PM, Brent Yorgey <byorgey at seas.upenn.edu> wrote:
>>
>> I know there are cases where this comes up in Haskell, but in certain
>> cases the needs arises only because of the way Haskell handles
>> typeclasses. What I mean is, if you had a function: something n =
>> [1..n], and your type was a -> [a], a needs to be declared as (Num a,
>> Enum a), even though this is sort of redundant, since you can't really
>> have a number that isn't also enumerable. I'm talking specifically
>> about cases where you'd have (TypeClass1 a, TypeClass2 a), and
>> TypeClass1 doesn't imply TypeClass2 or visa versa (Brandon's example
>> might have served that purpose, though I'm very new to Haskell and
>> haven't gotten a full grasp on monads yet).
>
> No, I really do mean that this comes up all the time in a nontrivial
> way.  Here's an example I just pulled randomly from a library of mine:
>
>  -- | Create a scale transformation.
>  scaling :: (HasLinearMap v, HasLinearMap (Scalar v),
>              Scalar (Scalar v) ~ Scalar v, Fractional (Scalar v))
>          => Scalar v -> Transformation v
>  scaling s = fromLinear $ (s *^) <-> (^/ s)
>
> None of those class constraints implies any of the others (not even in
> theory), and they are all necessary.
>
>> Ya but isn't that a pretty big hassle, especially assuming there are
>> many useful cases where you require a type to belong to multiple
>> typeclasses?
>
> Sure, it's a hassle, but you were looking for examples of why type
> classes are better than interfaces, and I'm not sure that simple
> matters of convenience really count.

For what I meant I'd classify that sort of convenience as a benefit. I
mostly was curious about Learn You a Haskell for Great Good's remark
that "You can think of [typeclasses] kind of as Java interfaces, only
better." Not having to create a new interface every time you want to
check for a different collection of typeclasses would qualify as
"better" for me.

>> Read through some of that (will probably read through more later), but
>> as I did it also occurred to me that I guess the typeclass system
>> might simply be a necessity to work with the rest of Haskell's type
>> system? Ie, the point of them isn't their benefits over interfaces,
>> it's that it's just the way things need to work in order to
>> effectively connect with algebraic types?
>
> No, you don't need type classes to use algebraic data types; see
> OCaml.  Type classes were a major innovation at the time they were
> added to Haskell, but algebraic data types had been around for a
> while.
>
> -Brent
>


More information about the Beginners mailing list