我现在正在尝试使用 IORef 在 Haskell 中创建一个简单的随机数生成器来存储可变变量。这个想法是我可以初始化种子,然后根据种子生成数字,并将新种子存储为下一个随机整数。
我得到的完整错误是:
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)))