3

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.

2
  • 2
    So, given an element in a 2D array, you need to find that element (presumably, unique?) and return the indices you found it at? That's certainly possible (but a bit odd for arrays, since it will mean a linear scan). How far have you got so far? Commented May 9, 2011 at 18:53
  • Yes, it's unique.. I think I'll have to iterate through the whole array and check if the value is the expected and then if it is, return it. But I don't know how to access the elements (individually) in the array. Commented May 9, 2011 at 19:23

3 Answers 3

6

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.

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

Comments

4

How about

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

Comments

0

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

Comments

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.