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

Anna
  • 41
  • 5
  • 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. – Jon Purdy May 05 '18 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. – fp_mora May 06 '18 at 15:53

2 Answers2

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.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
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
Igor Drozdov
  • 14,690
  • 5
  • 37
  • 53
  • But how do you adjust the function with this given type of nth? nth :: Matrix a -> Int -> Int -> a – Anna May 05 '18 at 10:20
  • @Asma but what are you going to receive, when your indices are too large and there is no element to return? – Igor Drozdov May 05 '18 at 10:35