[Haskell-cafe] STM, newArray, and a stack overflow?

Bas van Dijk v.dijk.bas at gmail.com
Thu Mar 24 01:22:19 CET 2011


On 23 March 2011 21:07, Ketil Malde <ketil at malde.org> wrote:
> Shouldn't it be possible to create an array in a loop with only constant
> memory overhead?

I think it should. Maybe we need something like this:

unsafeArrayM :: Ix i => (i, i) -> Int -> IO e -> IO (Array i e)
unsafeArrayM (l,u) n@(I# n#) (IO f) = IO $ \s1# ->
    case newArray# n# arrEleBottom s1# of
        (# s2#, marr# #) ->
            let go i# s#
                    | i# ==# n# =
                        case unsafeFreezeArray# marr# s# of
                          (# s3#, arr# #) -> (# s3#, Array l u n arr# #)
                    | otherwise =
                        case f s# of
                          (# s3#, x #) ->
                              case writeArray# marr# i# x s3# of
                                s4# -> go (i# +# 1#) s4#
            in go 0# s2#

The given IO computation can then be something like: unsafeIOToSTM $ newTVar e.

Note that I haven't compiled and tested this code at all nor thought
about it to deeply ;-)

Bas



More information about the Haskell-Cafe mailing list