I am working on a type class for fraction, vector, and matrix arithmetic (ie add, sub, mul) but can't quite get the vector instance because I don't know how to work with the recursive nature of the function.
here's the code:
class MathObject a where
add :: a -> a -> a
sub :: a -> a -> a
mul :: a -> a -> a
type Vector = [Int]
data Vec = Vec Vector deriving (Show, Eq)
instance MathObject Vec where
add (Vec v1) (Vec v2) = addVecs (Vec v1) (Vec v2)
sub (Vec v1) (Vec v2) = subVecs (Vec v1) (Vec v2)
mul (Vec v1) (Vec v2) = mulVecs (Vec v1) (Vec v2)
addVecs :: Vec -> Vec -> [Int]
addVecs (Vec []) (Vec vec2)= (Vec [])
addVecs (Vec vec) (Vec []) = (Vec [])
addVecs (Vec (x:xs)) (Vec (y:ys)) = e1+e2:rest where
e1 = x
e2 = y
rest = addVecs (Vec xs) (Vec ys)
subVecs :: Vec -> Vec -> [Int]
subVecs (Vec []) (Vec v2) = (Vec [])
subVecs (Vec (x:xs)) (Vec (y:ys)) = x-y:rest where
rest = subVecs (Vec xs) (Vec ys)
mulVecs :: Vec -> Vec -> [Vec]
mulVecs (Vec []) (Vec vec2) = (Vec [])
mulVecs (Vec (x:xs)) (Vec (y:ys)) = e1 * e2:rest where
e1 = x
e2 = y
rest = mulVecs (Vec xs) (Vec ys)
I made the fraction instance and it works so I have some basic understanding of how type classes work but I just don't know how to deal with a recursive type.