Skip to content

indexArray# getting poorly deferred

In both of the following functions I am attempting to execute a read from an Array# a and then write the result to a MutableArray# s a, and I would like the following evaluation properties:

  • the a value is not forced, i.e. the value stored in the MutableArray# s a will remain a thunk if the original value in the Array# a was; and
  • the new MutableArray# does not maintain any references to the original Array#, so that the original can be GCed.

The singleton-unboxed-tuple return type of indexArray# appears to be there to allow specifically this use case, but sadly it only succeeds for the first of these functions. The second function ends up storing a thunk in the MutableArray# which contains a reference to the Array#.

Haskell:

{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}

module IndexThenWrite where

import GHC.Prim

indexThenWrite :: Array# a -> MutableArray# s a -> State# s -> State# s
indexThenWrite arr marr s = case indexArray# arr 123# of
  (# a #) -> writeArray# marr 234# a s

indexThenWriteF :: (a -> b) -> Array# a -> MutableArray# s b -> State# s -> State# s
indexThenWriteF f arr marr s = case indexArray# arr 123# of
  (# a #) -> writeArray# marr 234# (f a) s

Core:

-- RHS size: {terms: 15, types: 18, coercions: 0, joins: 0/0}
indexThenWrite
indexThenWrite
  = \ @ a_aq9 @ s_aqa arr_apa marr_apb s1_apc ->
      case indexArray# arr_apa 123# of { (# ipv_sUH #) ->
      writeArray# marr_apb 234# ipv_sUH s1_apc
      }

-- RHS size: {terms: 18, types: 22, coercions: 0, joins: 0/0}
indexThenWriteF
indexThenWriteF
  = \ @ a_aq0 @ b_aq1 @ s_aq2 f_ape arr_apf marr_apg s1_aph ->
      writeArray#
        marr_apg
        234#
        (case indexArray# arr_apf 123# of { (# ipv_sUK #) ->
         f_ape ipv_sUK
         })
        s1_aph

I'd like the second function to generate code similar to the first.

Trac metadata
Trac field Value
Version 8.2.1
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information