I'm trying to make a simple random number generator in Haskell using IORef now to store mutable variables. The idea is that I can initialise the seed, and then generate numbers based on the seed, and store the new seed for the next random int.
The full error I'm getting is:
random2.hs:9:17:
Couldn't match type `IO Int' with `Int'
Expected type: IO (IORef Integer)
-> (IORef Integer -> IO Int) -> Int
Actual type: IO (IORef Integer)
-> (IORef Integer -> IO Int) -> IO Int
In a stmt of a 'do' block: seed <- newIORef 7
In the expression:
do { seed <- newIORef 7;
randomGen (readIORef seed) }
In an equation for `getRandom':
getRandom
= do { seed <- newIORef 7;
randomGen (readIORef seed) }
random2.hs:10:17:
Couldn't match type `(,) Int' with `IO'
Expected type: IO Int
Actual type: (Int, Int)
In the return type of a call of `randomGen'
In a stmt of a 'do' block: randomGen (readIORef seed)
In the expression:
do { seed <- newIORef 7;
randomGen (readIORef seed) }
random2.hs:10:28:
Couldn't match expected type `Int' with actual type `IO Integer'
In the return type of a call of `readIORef'
In the first argument of `randomGen', namely `(readIORef seed)'
In a stmt of a 'do' block: randomGen (readIORef seed)
Failed, modules loaded: none.
I don't understand how it can not be matching the type - I'm explicit that the randomGen takes/returns an Int. Here's my code:
module Main where
import Data.IORef
randomGen :: Int -> (Int, Int)
randomGen x = (x,x+1)
getRandom :: Int
getRandom = do
seed <- newIORef 7
randomGen (readIORef seed)
Any idea what's going on here?
Thanks,
Updated code:
module Main where
import Data.IORef
import Control.Monad
randomGen :: Int -> (Int, Int)
randomGen x = (x,x+1)
getRandom :: IO Int
getRandom = do
seed <- newIORef 7
liftM (fst (randomGen (readIORef seed)))