2

I'm trying to access specific element of matrix. For instance to get every second element of sublist and give as single list back.

data Matrix a = M [[a]]
rowMatrix :: [[Int]] -> Int -> a

for ex rowMatrix [[1,2,3,4], [5,6,7,8],[9,10,11,12]] 3 ---> [3,7,11]

3 Answers 3

1

We can, for each row, obtain the k-th element, so we can perform a mapping, like:

romMatrix :: [[a]] -> Int -> [a]
rowMatrix m k = map (!! k) m

Or for a Matrix type:

romMatrix :: Matrix a -> Int -> [a]
rowMatrix (M m) k = map (!! k) m

So here we create a list of elements where each element is the k-th element of the corresponding sublist.

Sign up to request clarification or add additional context in comments.

Comments

1

For each sublist, extract its nth element with the !! operator:

rowMatrix [] _ = []
rowMatrix (row:others) n = (row !! n) : (rowMatrix others n)

For example:

rowMatrix [[1,2,3], [2,3,4]] 2
[3,4]

You can also make this a bit crazier, but also more concise:

rowMatrix :: [[a]] -> Int -> [a]
rowMatrix listOfLists n = listOfLists >>= ((:[]) . (!! n))

4 Comments

somehow im getting compiler error, did you test it?
@mWelt: I think you confuse your Matrix data type and the signature of your function.
@mWelt, this is written for the underlying list type, and it shouldn't be hard to make this work for Matrix: some pattern matching should do the trick.
you both are right, i saw where i failed. thanks @WillemVanOnsem exactly was my confusing point
0

Since rows are columns in the transposed matrix; to fit with your example; it is just

rowMatrix :: [[a]] -> Int -> [a]
rowMatrix xs m = transpose xs !! (m-1)

I had to fix your type, too. Also note the off-by-1 issue.

> rowMatrix [[1,2,3,4], [5,6,7,8], [9,10,11,12]]  3
[3,7,11]
it :: [Int]

2 Comments

Actually it works with my type too, input does not have to be Int, could be any list of a. but your solution is also cool.
in that case, it should be [[a]] -> Int -> [a].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.