Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix constructor and method in Haskell

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]]

like image 553
nobody Avatar asked Dec 10 '22 05:12

nobody


1 Answers

Are you having a problem with defining a Num instance for your type? Try this code:

data Matrix a = Matrix [[a]]
              deriving (Eq)

plus_mat :: Num a => [[a]] -> [[a]] -> [[a]]
plus_mat = zipWith (zipWith (+))

instance Num a => Num (Matrix a)
  where
    (Matrix a) + (Matrix b) = Matrix $ plus_mat a b
    (-)                     = undefined
    (*)                     = undefined
    negate                  = undefined
    abs                     = undefined
    signum                  = undefined
    fromInteger             = undefined

Testing:

*Main> Matrix [[1,2],[3,4]] + Matrix [[5,6],[7,8]]
Matrix [[6,8],[10,12]]

Definitions of the remaining class methods are left as exercise.

And here's a Show instance for Matrix:

import Data.List

instance Show a => Show (Matrix a)
  where
    show (Matrix a) = intercalate "\n" $ map (intercalate " " . map show) a

Testing:

*Main Data.List> Matrix [[1,2,3], [4,5,6]]
1 2 3
4 5 6
like image 78
Mikhail Glushenkov Avatar answered Dec 23 '22 13:12

Mikhail Glushenkov