[Haskell-beginners] Type inference in ST monad?

Aurimas aurimas.anskaitis at vgtu.lt
Mon Aug 19 03:18:28 CEST 2013


I have the following code which does not compile due to explicit type 
annotation
(ST s Double). Error message says usual thing about "s" type variables.

----------------------------------------------------------------------------------------------------------
import Control.Monad.ST
import System.Random.MWC (initialize, uniformR, Gen)
import Control.Monad.Loops (whileM)
import Data.Vector (singleton)
import Data.Word(Word32)

main :: IO ()
main = do
   print $ runSimulation 1

runSimulation :: Word32 -> [Int]
runSimulation seed = runST $ do
   gen <- initialize (singleton seed)
   whileM  (do r1 <- uniformR (-1.0, 1.0) gen :: ST s Double -- does not 
compile due to this
               if r1 > 0.0 then return True else return False)
           (do r2 <- uniformR (0, 10) gen
               if r2 > 5 then return r2 else return 0)
---------------------------------------------------------------------------------------------------------

if I rewrite runSimulation like this (below), everything is OK.

---------------------------------------------------------------------------------------------------------
runSimulation :: Word32 -> [Int]
runSimulation seed = runST $ do
   gen <- initialize (singleton seed)
   whileM  (do r1 <- tempFun gen
               if r1 > 0.0 then return True else return False)
           (do r2 <- uniformR (0, 10) gen
               if r2 > 5 then return r2 else return 0)
     where tempFun :: Gen s -> ST s Double    -- this line automatically 
provides required type annotation
           tempFun g = uniformR (-1.0, 1.0) g
---------------------------------------------------------------------------------------------------------

Ca somebody explain what's wrong with the first version?

Best Regards,
Aurimas





More information about the Beginners mailing list