Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use `getBounds' with STArray?
    primarykey
    data
    text
    <p>I'm trying to write a Fisher-Yates shuffle algorithm using STArray. Unlike all the other examples I've found on the net, I am trying to avoid using native lists. I just want to shuffle an array, in-place.</p> <p>This is what I have:</p> <pre><code>randShuffleST arr gen = runST $ do _ &lt;- getBounds arr return (arr, gen) </code></pre> <p><code>arr</code> is the STArray and <code>gen</code> will be a generator state of type (RandomGen g).</p> <p>I was hoping I could rely on the <code>(MArray (STArray s) e (ST s))</code> <a href="http://hackage.haskell.org/packages/archive/array/0.4.0.1/doc/html/Data-Array-MArray.html" rel="nofollow">instance declaration</a> defined in MArray for being able to use MArray's <code>getBounds</code> but GHCi cannot infer the type of <code>randShuffleST</code>. It fails with:</p> <pre><code>Could not deduce (MArray a e (ST s)) arising from a use of `getBounds' from the context (Ix i) bound by the inferred type of randShuffleST :: Ix i =&gt; a i e -&gt; t -&gt; (a i e, t) at CGS/Random.hs:(64,1)-(66,25) Possible fix: add (MArray a e (ST s)) to the context of a type expected by the context: ST s (a i e, t) or the inferred type of randShuffleST :: Ix i =&gt; a i e -&gt; t -&gt; (a i e, t) or add an instance declaration for (MArray a e (ST s)) In a stmt of a 'do' block: _ &lt;- getBounds arr In the second argument of `($)', namely `do { _ &lt;- getBounds arr; return (arr, gen) }' In the expression: runST $ do { _ &lt;- getBounds arr; return (arr, gen) } </code></pre> <p>Interestingly, if I remove the call to `runST' like so:</p> <pre><code>randShuffleST arr gen = do _ &lt;- getBounds arr return (arr, gen) </code></pre> <p>it compiles fine, with the type signature</p> <pre><code>randShuffleST :: (Ix i, MArray a e m) =&gt; a i e -&gt; t -&gt; m (a i e, t) </code></pre> <p>. I'm using GHC 7.4.2 on Arch Linux.</p> <p>Please give explicit type signatures in your responses to help me understand your code, thank you.</p> <p>EDIT: I really like Antal S-Z's answer, but I cannot select it because frankly I do not fully understand it. Maybe once I understand my own problem better I'll answer my own question in the future... thanks.</p>
    singulars
    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. 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