我正在嘗試使用MonadRandom
。我把它放到了randomPref
的功能中,但是整件事情都事後起來了!任何提示都表示讚賞。如何重構代碼以使用MonadRandom
module AgentGenerator where
import System.Random
import Data.Hashable
import Control.Monad.Random
import System.Environment
-- Generate agents and write to a file
-- 'fname' - output filename
-- 's' - number of agent sets
-- 'n' - number of agents in a set
-- 'x' - number of preferences per agent
generate fname s n x = do
writeFile fname $ show $ generateAgentSets s n x
-- Agent type: Name, List of preferences
data Agent = Agent String [Double] deriving Show
type AgentSet = [Agent]
-- Generate 's' sets of 'n' agents each, with 'x' preferences each
generateAgentSets:: Integer -> Integer -> Integer -> [AgentSet]
generateAgentSets s n x = [generateAgents n x | i <- [1..s] ]
-- Generate n agents with 'x' preferences each
generateAgents:: Integer -> Integer -> AgentSet
generateAgents n x = [createAgent (show i) x | i <- [1..n]]
-- Create agent 'name' with 'x' preferences
createAgent:: String -> Integer -> Agent
createAgent name x = Agent name prefs where
prefs = [ randomPref (i + hashed) | i <- [1..x] ] where
hashed = fromIntegral (hash name)
-- Generate single random value between [0, 1] based on the seed
-- TODO: Get rid of the seed thing and use MonadRandom instead
randomPref :: (RandomGen g) => Integer -> Rand g [Double]
randomPref seed = getRandomR (0.0, 1.0)
謝謝你,你是對我的'randomPref'不應該返回一個列表 - 我剛剛發現這個類型簽名'蘭德G [雙]'的地方,並在不知不覺中使用它。而'seed'是舊代碼的遺蹟 - 未使用'MonadRandom' - 事實上,除了'一切randomPref'是不使用'MonadRandom'代碼 - 因爲我只是想弄清楚後就放棄瞭如何使用該死的東西!對困惑感到抱歉。 – drozzy 2012-02-15 13:04:50
當我嘗試使用'產生「out.txt」從控制檯2個10 3 getStdGen'我得到'不實例(RandomGen(IO StdGen))'錯誤:-( – drozzy 2012-02-15 15:23:49
getStdGen返回一元價值,所以你需要做的'getStdGen >> =生成 「out.txt」 2 10 3',或者可替換地,可以使用'生成 「out.txt」 2 10 3(newStdGen種子)'。所不同的是'getStdGen'返回全球,共享隨機數發生器和'newStdGen'創建一個基於種子值一個新的隨機生成。 – shang 2012-02-15 15:36:51