Breno Inojosa
Breno Inojosa

Reputation: 602

Haskell Array(Matrix) Element Access

I'm currently in a project that will need to access elements in an Array-Matrix in Haskell. So, I've tried googling it, searching everywhere.

The funcion is supposed to be like this:

getElementIndex :: Int -> Array (Int,Int) Int -> (Int,Int)

And it must return the I and J indexes of the element in the matrix.

Upvotes: 3

Views: 5430

Answers (3)

Simon
Simon

Reputation: 3110

Simple Matrixs in Preclude http://www.haskell.org/haskellwiki/Prelude_extensions#Matrices

Upvotes: 0

Don Stewart
Don Stewart

Reputation: 137947

To read elements from Array types in Haskell, you use the (!) operator, as in:

Prelude Data.Array> let v = listArray (0,9) [1..10]
Prelude Data.Array> v ! 3
4

so, now all you need to do is walk the index space, rows and columns. I like list comprehensions for that kind of task:

assocs' x y arr = [ ((i,j), arr ! (i,j))
                  | i <- [0..x-1]
                  , j <- [0..y-1]
                  ]

which is just a specialized version of Data.Array.assocs:

assocs :: Ix i => Array i e -> [(i, e)]

which returns a lazy list of indices and elements. So, call assocs, and then take the first element that matches.

Upvotes: 6

fuz
fuz

Reputation: 92994

How about

\x -> map fst . filter ((==x) . snd) . assocs

Upvotes: 4

Related Questions