开发者

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) I开发者_Python百科nt -> (Int,Int)

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


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.


How about

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜