Anna
Anna

Reputation: 41

Multiple lists haskell

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

Upvotes: 1

Views: 1440

Answers (2)

Igor Drozdov
Igor Drozdov

Reputation: 15045

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

Upvotes: 2

Yann Vernier
Yann Vernier

Reputation: 15877

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.

Upvotes: 4

Related Questions