tsorn
tsorn

Reputation: 3625

runST inside MonadRandom

I want to do runST inside a Rand-monad, but I can't get the types right and the output from GHC is not particularly helpful:

import           Control.Monad
import           Control.Monad.Random as MR
import           Control.Monad.ST
import           Control.Monad.Trans
import qualified Data.Vector.Unboxed  as VU

shuffle :: (MonadRandom m) => m (VU.Vector Int)
shuffle = do
  k <- getRandomR (0::Int, 10::Int)
  let vec = runST $ do
    vector <- VU.unsafeThaw (VU.enumFromN (1::Int) k)
    vector' <- VU.unsafeFreeze vector
    return vector
  return vec

parse error on input `vector'

Upvotes: 0

Views: 82

Answers (1)

Erik
Erik

Reputation: 957

That error is usually related to indentation issues. If you indent the lines in the runST block a bit more, that error will go away.

The next issue is that you're returning the wrong vector (forgot the ').

Lastly, binding a value only to use it with the return function on the next line is redundant.

Here is working code:

shuffle :: (MonadRandom m) => m (VU.Vector Int)
shuffle = do
  k <- getRandomR (0::Int, 10::Int)
  let vec = runST $ do
              vector <- VU.unsafeThaw (VU.enumFromN (1::Int) k)
              VU.unsafeFreeze vector
  return vec

Alternatively,

shuffle :: (MonadRandom m) => m (VU.Vector Int)
shuffle = do
  k <- getRandomR (0::Int, 10::Int)
  return $ runST $ do
    vector <- VU.unsafeThaw (VU.enumFromN (1::Int) k)
    VU.unsafeFreeze vector

Upvotes: 2

Related Questions