views:

364

answers:

3

hi I have a question about haskell coding.

Matrices

One of many ways to define matrices in Haskell is the list of matrix rows, where a row is a list of double precision oating point numbers:

type Matrix=[[Double]]

Using this type you should define the following functions (definition of dim is given as an inspirational example).

dim :: Matrix -> (Int,Int) --returns matrix dimension (number of rows and columns)
dim m = if (not.isMatrix) m then error "Not a matrix" else (length m, length (head m))

isMatrix :: Matrix -> Bool --checks whether all rows have the same length
isMatrix m =  and [length (head m) == length a | a <- m]

I have done upto here and I am stuck on multSM.

multSM :: Double -> Matrix -> Matrix --multiplies a scalar and a matrix

when I do:

multSM  d m = [[(b*a)| b<-[d], a<-(head m)]] or [map (*d) (head m)]

...I get (using Hugs):

Main> multSM 3 [[2,3,4],[1,3,4],[6,3,0]]
[[6.0,9.0,12.0]]

So I solve 3 [2,3,4] but I do not know how to get the rest 3 [[1,3,4],[6,3,0].

Please help me on this problem.

These are rest of unsolved questions if anyone can help with:

Thank you~

+3  A: 
multSM k = map (map (k *))
transp = Data.List.transpose
addM = zipWith (zipWith (+))
trinithis
it's not working
Kwan
oh i got multSM addM thanks but transp is not yet doing Undefined qualified variable "Data.List.transpose"
Kwan
@Kwan: You need to either `import qualified Data.List`, or `import Data.List` and change it to simply `transpose`.
ephemient
A: 

I wrote up a Vector/Matrix module years ago, with some extra notes here.

ephemient
A: 

You almost did it. When you do

[ f x | x <- someList]

you can understand this as: 1) get an element from someList, 2) apply f, 3) append to a list and go to step 1 again.

But this is exactly map f someList

So try:

lineMul x line = [x * element | element <- line]
scalarMul x matrix = [lineMul x line | line <- matrix]

But note that you can rewrite this as:

lineMul x line = map (x*) line
scalarMul = map (lineMul x) matrix

And join them in a single expression:

scalarMul x matrix = map $ map (x*) $ matrix

Or even skip the last argument, as it's type is already fixed by the definition of map:

scalarMul x = map $ map (x*)
Rafael S. Calsaverini