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

minh thu noteed at gmail.com
Fri Jan 23 18:10:38 EST 2009


2009/1/24 Dan Piponi <dpiponi at gmail.com>:
> 2009/1/23 Olex P <hoknamahn at gmail.com>:
>
>> 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.
>
> It works fine if you make Matrix3 an instance of Vector.
> --
> Dan

To paraphrase a bit, your Vector class simply means :
a type is a Vector if it provides an operation having a -> a -> a
has its type (and called ^+^).

The Matrix class says exactly the same thing, so don't bother
repeat that... and simply make Vector3 and Matrix3 instances
of Vector (which could then be renamed in Add or Plus or
something).

Thu


More information about the Haskell-Cafe mailing list