我想在Haskell中使用IORef来创建一个简单的随机数生成器来存储可变变量。我的想法是,我可以初始化种子,然后根据种子生成数字,并为下一个随机int存储新种子。Simple Haskell IORef - “无法与`Int'匹配'IO Int'类型” - 看不到它有什么不同
完整的错误,我得到的是:
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.
我不明白怎么就不能匹配的类型 - 我明确了randomGen采取/返回一个int。这里是我的代码:
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)
任何想法这里发生了什么?
感谢,
更新代码:
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)))
'randomGen'是纯粹的,但'readIORef'返回'IO a'。你将在do子句中的'randomGen'前使用'liftM'。另外'getRandom :: IO Int'。一旦它是IO,你无法摆脱它。 – dumb0
@ dumb0所以我添加了导入Control.Monad,将'getRandom :: Int'的def更改为'getRandom :: IO Int',并将最后一行从'randomGen(readIORef seed)'改为'liftM(randomGen(readIORef种子))' - 这是你所描述的吗?因为这会引发另一个错误。 –
我的评论有一个错误它的:'getRandom :: IO(Int,Int)' – dumb0