So here is a nested list [[1, 2], [3, 4]]
I want to wrap it in a type called Matrix, and make it an instance of the classes Eq, Num, and Show
I have already created (add, sub, mul) operations for nested lists (matrices). How do I overload (+ – *) operators so that + maps to add, – maps to sub, and * maps to mul? So I can do this
> ma = Matrix [[1, 2], [3, 4]]
> mb = Matrix [[5, 6], [7, 8]]
> ma + mb
> ma - mb
> ma * mb
Thanks
EDIT
this is my attempt so far
> add = zipWith (zipWith (+)) > sub = zipWith (zipWith (-)) > data Matrix a = Matrix [[a]] deriving (Eq, Show) > instance Num (Matrix a) > where > (+) x y = Matrix $ add x y > (-) x y = Matrix $ sub x y
This is what I get from ghci
Couldn't match expected type `[[c0]]' with actual type `Matrix a'
In the first argument of `sub', namely `x'
In the second argument of `($)', namely `sub x y'
In the expression: Matrix $ sub x y
EDIT #2
The last thing I need to figure out right now is
how to I print
1 2 3 4
Instead of Matrix [[1,2],[3,4]]
Are you having a problem with defining a
Numinstance for your type? Try this code:Testing:
Definitions of the remaining class methods are left as exercise.
And here’s a
Showinstance forMatrix:Testing: