Recently I tried implementing linear maps class for 2d vectors. It was fine until I tried to change the base type (base-ring) of vectors to a generic one. I have the following type for vectors:
data Vector a = V a a
(As far as I know, I can't or shouldn't specify what a
is.)
And I want to have a class (not a type) for linear maps. The reason behind it: I want to have a very specific linear maps, say rotations, that depends on a different set of parameters (and may even not depend on any params, for example x-reflection have no params), but they all have one purpose -- apply to vector (that is why I call it a class).
I tried defining the following class
class LinearMap m where
apply :: m -> Vector a -> Vector a
And say I want two instances
data Rotation a = Rot a
instance LinearMap (Rotation a) where
Rot phi `apply` V x y = V (c * x - s * y) (s * x + c * y)
where
(c, s) = (cos phi, sin phi)
but it gives me an error, because I expected a type
apply :: Rotation a -> Vector a -> Vector a
while compiler expected
apply :: Rotation a -> Vector b -> Vector b
And even if type binding is not a problem as in the following
data Reflection = XRefl | YRefl
instance LinearMap Reflection where
XRefl `apply` V x y = V (-x) y
YRefl `apply` V x y = V x (-y)
I get an error, because now x
and y
must be instances of Num
,
but I don't see where I should write the instance.
An easy option would be to edit the LinearMap
class and add something like
class LinearMap m where
apply :: Num a => m -> Vector a -> Vector a
but it is not what I was trying to do (I hope you see my motivation),
and it doesn't solve the Rotation
problem, either.
UPD: Here is what I came up with (not quite happy)
class LinearMap m a | m -> a where
apply :: m -> Vector a -> Vector a
Now Rotation
is fine:
instance Floating a => LinearMap (Rotation a) a where
-- apply = ...
But Reflection
needs an update
data Reflection a = XRefl | YRefl
so I can define an instance
instance Num a => LinearMap (Reflection a) a where
-- apply = ...
Because a
depends on m
as in LinearMap
class definition.
But now I'm not happy that Reflection
depends on something (it shouldn't right?).
Num
, so if you use it, your base ring/field is automatically restricted toNum
.