[Haskell-beginners] Stymied by mutable arrays in the ST monad

Tobias Brandt tob.brandt at googlemail.com
Fri May 25 19:05:01 CEST 2012


On 25 May 2012 18:50, Matthew Moppett <matthewmoppett at gmail.com> wrote:
> I've been trying to use mutable arrays in the ST monad, and wrote out a
> little proof of concept function:
>
> idST :: [Int] -> [Int]
> idST xs = runST $ do
>     array <- newListArray (1, (length xs)) xs
>     return (getElems array)
>
> -- where idSt should be equivalent to id.
>
> And I get the error message:
>
> Couldn't match type `[Int]' with `Int'
>     In the return type of a call of `getElems'
>     In the first argument of `return', namely `(getElems array)'
>     In a stmt of a 'do' block: return (getElems array)
>
> Obviously I'm making a very simple mistake here, but I can't seem to spot
> it. Can anyone offer some advice?

'getElems array' already has type 'ST s [Int]', you don't need
another 'return'. Furthermore you need to help out with the type
inference a little bit (it's similar to the read-show problem).
This should work:

idST :: [Int] -> [Int]
idST xs = runST $ do
    array <- newListArray (1, (length xs)) xs :: ST s (STArray s Int Int)
    getElems array

(You could also replace STArray by STUArray.)



More information about the Beginners mailing list