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

Matthew Moppett matthewmoppett at gmail.com
Fri May 25 19:43:04 CEST 2012


Thanks, Tobias.

I guess my eyes kind of glazed over when I read "getElems :: (MArray a e
m, Ix i) => a i e -> m [e]" in the docs, and didn't relate that to the
meaning of "return"... lesson learnt.

About the extra type info needed -- what part of the type "ST s (STArray s
Int Int)" is the compiler unable to infer?

I've worked out from this that the error message "no instance for"... might
signal a missing type signature, but I'm having trouble working out the
general lesson of when the compiler needs some extra hints.


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.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120526/04e7ba17/attachment.htm>


More information about the Beginners mailing list