[Haskell-cafe] zip, map and zipWith for arrays

ok ok at cs.otago.ac.nz
Sun Sep 9 23:03:34 EDT 2007

On 9 Sep 2007, at 10:05 pm, Axel Gerstenberger wrote:
> I am used to work with map, zip and zipWith, when working with  
> lists, however, I could not find such functions for Arrays.

They aren't there for at least two reasons.
(1) They are easy to implement on top of the operations that are
     provided.  (EASY is not the same as EFFICIENT, of course.)
(2) In some cases it isn't obvious what the operations should be.

I note as a counter-argument that Clean provides, in addition to
list comprehension and list generators,
array comprehension and array generators,
so maps and zips of any arity are directly and transparently
available in a very Haskell-like language.

I note as a counter-counter-argument that Clean is free of Haskell's
"Ix" baggage, which takes us back to (2).

zip being a special case of zipWith, let's consider just map and  

amap :: Ix i => (a -> b) -> Array i a -> Array i b

amap f arr = listArray (bounds arr) (map f (elems arr))

A more general version of this is available, under that name,
in Data.Array.IArray, and Data.Array.MArray gives you mapArray.

aZipWith :: Ix i => (a -> b -> c) -> Array i a -> Array i b -> Array i c

aZipWith f a1 a2 =
   if bounds a1 == bounds a2 then
      listArray (bounds a1) (zipWith f (elems a1) (elems a2))
   else error "aZipWith: array bounds do not agree"

But do you really want aMap's result to have the same bounds as its
argument?  If not, what bounds do you want it to have?  Do you want
aZipWith to fail if the arrays haven't exactly the same bounds, or
do you want to work with the intersection of their bounds, or what?

A worse problem these days is that in the dotted libraries there are
so *many* variants of arrays.  We need to start writing stuff like

	aZipWith :: (Ix i, IArray a1 e1, IArray a2 e2, IArray a3 e3) =>
		    (e1 -> e2 -> e3) -> a1 i a1 -> a2 i e2 -> a3 i e3

and this is deeper waters than I am comfortable swimming in.

(What's the best thing to read to explain functional dependencies for
multi-parameter type classes?)

More information about the Haskell-Cafe mailing list