[Haskell-cafe] dimension of arrays

Josef Svenningsson josefs at cs.chalmers.se
Mon Mar 29 17:05:19 EST 2004


On Mon, 29 Mar 2004, Fred Nicolier wrote:

> Is there a way to get the number of dimension of an array ? i.e.
> something like :
>
>  >dims :: (Ix a) => Array a b -> Int
>  >dims = ...
>  >a = listArray (1,10) [1,2..]
>  >b = listArray ((1,1),(10,10)) [1,2..]
>  >dims a -- should be equal to 1
>  >dims b -- should be equal to 2
>
> The key is somewhere in the Ix class but where ?
>
In a sense Haskell arrays are always one dimensional. But as you noted
tuples are used to achieve higher dimensionality. As far as I know there
is no way of asking for the dimension of an array. You could write your
own class for that though. Here's a suggestion:

\begin{code}
dims :: (Ix a, HasDimension a) => Array a b -> Int
dims arr = dimension (head (range arr))

class HasDimension a where
  dimension :: a -> Int

instance HasDimension Int where
  dimension _ = 1

instance HasDimension Float where
  dimension _ = 1

instance HasDimension (a,b) where
  dimension _ = 2

instance HasDimension (a,b,c) where
  dimension _ = 3
\end{code}

And so forth. Beware. The code is untested.

Hope this helps.

	/Josef


More information about the Haskell-Cafe mailing list