Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>How are arrays, having O(1) time to access or modify an indexed element, implemented in Haskell</p> </blockquote> <p>They are implemented via primitive operations in the runtime system for memory reads and writes.</p> <p>The safety of the side effecting action of destructively writing to memory is ensured via the use of monads to linearize access to the mutable state.</p> <p>Looking at the <a href="http://hackage.haskell.org/package/primitive" rel="noreferrer"><code>primitive</code></a> package for Haskell arrays (in <code>IO</code> or <code>ST</code>), you can see that the implementations is in terms of <a href="http://hackage.haskell.org/trac/ghc/wiki/Commentary/PrimOps" rel="noreferrer">GHC's <em>primops</em></a>:</p> <pre><code>-- | Create a new mutable array of the specified size and initialise all -- elements with the given value. newArray :: PrimMonad m =&gt; Int -&gt; a -&gt; m (MutableArray (PrimState m) a) newArray (I# n#) x = primitive (\s# -&gt; case newArray# n# x s# of (# s'#, arr# #) -&gt; (# s'#, MutableArray arr# #)) -- | Read a value from the array at the given index. readArray :: PrimMonad m =&gt; MutableArray (PrimState m) a -&gt; Int -&gt; m a readArray (MutableArray arr#) (I# i#) = primitive (readArray# arr# i#) -- | Write a value to the array at the given index. writeArray :: PrimMonad m =&gt; MutableArray (PrimState m) a -&gt; Int -&gt; a -&gt; m () writeArray (MutableArray arr#) (I# i#) x = primitive_ (writeArray# arr# i# x) </code></pre> <p>That is, in terms of:</p> <ul> <li>newArray#</li> <li>readArray#</li> <li>writeArray#</li> </ul> <p>which are primitive (hardware accelerated ;) services for operating on memory provided by the language runtime.</p> <p>Mechanisms for giving type safety to destructive memory effects were introduced to Haskell by the Launchbury and Peyton-Jones paper, <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.50.3299" rel="noreferrer"><em>Lazy Functional State Threads</em></a>, which introduces the <code>ST</code> monad and primitives for mutable arrays.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload