1

How do you find nth elements in the matrix at a given row and column position? For example, if you have

type Matrice a = [[a]]

example :: Matrice Int  
example = [ [3, 5],                
        [2, 1],                
        [0, 4],                
        [6, 8] ] 

Prelude >  example 0 1
      5
Prelude >  example 2 0
      0
Prelude >  example 1 1
      2

I know how to work out with only given list such as

nth :: Int -> [a] -> Maybe a
nth _ []       = Nothing
nth 1 (x : _)  = Just x
nth n (_ : xs) = nth (n - 1) xs

But my question is, how do you access nth element in a matrix as in the given example

2
  • Side note: there’s no such thing as a “matrice”—singular is “one matrix”, plural is “some matrices”, same as vertex/vertices, index/indices, appendix/appendices, &c. Commented May 5, 2018 at 15:16
  • f ls m n = ls!!m!!n the matrix is given in ls, the list within the matrix is m and the element of the specified list is n ... [[a]] -> Int -> Int -> a ... If you want to do error checking in your function, do so but maybe use the !! operator. Commented May 6, 2018 at 15:53

2 Answers 2

4

Just handle each list individually, and !! will work:

Prelude> example
[[3,5],[2,1],[0,4],[6,8]]
Prelude> :t example
example :: Matrice Int
Prelude> example !! 0 !! 1
5

But lists are probably not the right data structure for this, because indexing is O(n). Depending on your task, Data.Vector or Data.Array may be better suited. See also Haskell: Lists, Arrays, Vectors, Sequences.

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

Comments

2

!! can be used for accessing an element by index, but be careful, since it's raising an exception, if the index is too large.

example !! 2 !! 0

And you've already written a function for accessing nth element of a list, just apply it twice:

nth :: Int -> Int -> [[a]] -> Maybe a
nth k n matrix = nth' n =<< nth' k matrix
  where
    nth' _ [] = Nothing
    nth' 0 (x: _) = Just x
    nth' n (_ : xs) = nth' (n - 1) xs

Or using your created Matrice type:

nth :: Matrice a -> Int -> Int -> Maybe a
nth matrix k n = nth' n =<< nth' k matrix
  where
    nth' _ [] = Nothing
    nth' 0 (x: _) = Just x
    nth' n (_ : xs) = nth' (n - 1) xs

2 Comments

But how do you adjust the function with this given type of nth? nth :: Matrix a -> Int -> Int -> a
@Asma but what are you going to receive, when your indices are too large and there is no element to return?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.