[Haskell-cafe] How to define an operation in terms of itself (but of different type)?

Jonathan Cast jonathanccast at fastmail.fm
Fri Jan 23 18:34:53 EST 2009


On Fri, 2009-01-23 at 22:58 +0000, Olex P wrote:
> Well if telepaths on vacation...
> 
> class Vector v where
>     (^+^)       :: v -> v -> v
> 
> data Vector3 = V3 !Double !Double !Double
> 
> instance Vector Vector3 where
>     (V3 x1 y1 z1) ^+^ (V3 x2 y2 z2) = V3 (x1 + x2) (y1 + y2) (z1 + z2)
> 
> class Matrix m where
>     (^+^)     :: m -> m -> m
> 
> 
> data Matrix3 = M3 !Vector3 !Vector3 !Vector3
> 
> 
> instance Matrix Matrix3 where
> 
>     (M3 r11 r12 r13) ^+^ (M3 r21 r22 r23) = M3 (r11 ^+^ r21)
>                                                                   (r12
> ^+^ r22)
>                                                                   (r13
> ^+^ r23)
> 
> 
> Hope this is better :)
> So yeah... r11 ^+^ r21 just doesn't work. 

I think you mis-understand how classes work in Haskell.  They aren't
like classes in OO languages.  They're a little bit like interfaces in
OO languages, but here we see another difference: in OO, you know an
object has a certain class, so you use that to find out what a method
name means.  In Haskell, it's the other way around: you know a method
belongs to a certain class, so you know its argument (or result) must
come from an instance of that class.  You can't re-use method names for
multiple classes, though - you have to either use different names (e.g.,
div vs. (/) in Prelude) or use a common base class.

jcc




More information about the Haskell-Cafe mailing list