views:

379

answers:

4

My problem is that I need to iterate over array and calculate some value depend on every element. I was looking for some fold-like function for arrays, but standard library seems to be very useless with arrays. Or i'm missing something?

The other solution may be 'binding' array to a list. Binding mean that I don't want to copy that array. Is this possible?

Btw, its all about plain Array.

+3  A: 

I just so happened to run across this article the other day: Folding Arrays

J Cooper
Thanks. I'm just wondering why such functions aren't in Data.Array?
qba
iirc, it was decided that since arrays can be multidimensional, a general fold function didn't make much sense. If you noticed, that article only covers some ways to fold over one-dimensional arrays
J Cooper
Actually they are! but only in the form of an instance for Data.Foldable.Foldable. They don't exist with their own names because that would just clutter up the namespace further. When in doubt check what classes have instances for the data type you are using.
Edward Kmett
+3  A: 

Take a look at Data.Foldable. It defines a type class that does exactly what you want.

Tirpen
+1  A: 

What kind of array type are you using? You may be able to just foldM over the index space.

Or use one of the array libraries that directly support folds (uvector).

Don Stewart
A: 

Using Data.Foldable you can foldr/foldl an Array just like you can a list.

Another option is that you can convert the Array back into a list with elems, and then foldr or foldl over the list.

Edward Kmett
Unfortunately this array is pretty big, so it takes too long to use elems.
qba