# [Haskell-cafe] Trying to use more than one array in runSTUArray

Anthony Cowley acowley at seas.upenn.edu
Thu Mar 15 19:53:56 CET 2012

```On Thursday, March 15, 2012 at 2:27 PM, Juan Miguel Vilar wrote:
> Hello, café:
>
> I am trying to use more than one array with runSTUArray but I don't seem
> to be able to understand how it works. My first try is this:
>
> test1 n = runSTUArray \$ do
> a <- newArray (1, n) (2::Int)
> b <- newArray (1, n) (3::Int)
> forM_ [1..n] \$ \i -> do
> v <- readArray a i
> writeArray b i (v+1)
> return b
>
> but it does not work. However, when I write

The problem is that GHC doesn't know what type of array a is. If you provide an annotation, you can resolve the ambiguity:

a <- newArray (1,n) (2::Int) :: ST s (STUArray s Int Int)

However, this is somewhat ugly, so we should look at your next example:

>
> test2 n = runSTUArray \$ do
> let createArray v n = newArray (1, n) (v::Int)
> a <- createArray 2 n
> b <- createArray 0 n
> forM_ [1..n] \$ \i -> do
> v <- readArray a i
> writeArray b i (v+1)
> return b
>
>

Note that the type of the b array was never in doubt thanks to runSTUArray. What you've done here is said that the same function that creates b also creates a, and since we know b's type, we now know a's type because GHC doesn't make createArray's type as polymorphic as it might.

Another approach to resolving the types is to essentially do what you've done in your second example, but give createArray a type that is as polymorphic as you need:

{-# LANGUAGE FlexibleContexts #-}

newSTUArray :: (MArray (STUArray s) e (ST s), Ix i) =>
(i,i) -> e -> ST s (STUArray s i e)
newSTUArray = newArray

test3 n = runSTUArray \$ do
a <- newSTUArray (1, n) False
b <- newSTUArray (1, n) (3::Int)
forM_ [1..n] \$ \i -> do