所以Random類包括Random
類,它是一類值你可以隨機生成(而不是你所期望的東西,發電機的這可以爲你製作隨機值)。
可以通過聲明添加對到Random類:
instance (Random x, Random y) => Random (x, y) where
randomR ((lo_x, lo_y), (hi_x, hi_y)) g = ((rand_x, rand_y), g'')
where (rand_x, g') = randomR (lo_x, hi_x) g
(rand_y, g'') = randomR (lo_y, hi_y) g'
random g = ((rand_x, rand_y), g'')
where (rand_x, g') = random g
(rand_y, g'') = random g'
這是一個複雜的定義,我知道,但你的代碼應能正常工作。
注意:您的代碼會導致您生成一個列表[a,b],其中的a == b
可能不是您想要的。你可能想看看進入State
單子在Control.Monad.State.Lazy
,您可以用之類的初始化:
state (randomR (1, 100)) :: State StdGen Int
這個單子明確鏈g
參數給你,所以:
ghci> :m +System.Random
ghci> :m +Control.Monad.State.Lazy
ghci> let dice_3d6 = mapM (state . randomR) (replicate 3 (1, 6)) :: State StdGen [Int]
Loading package array-0.4.0.1 ... linking ... done.
Loading package deepseq-1.3.0.1 ... linking ... done.
Loading package bytestring-0.10.0.2 ... linking ... done.
Loading package Win32-2.3.0.0 ... linking ... done.
Loading package transformers-0.3.0.0 ... linking ... done.
Loading package old-locale-1.0.0.5 ... linking ... done.
Loading package time-1.4.0.1 ... linking ... done.
Loading package random-1.0.1.1 ... linking ... done.
Loading package mtl-2.1.2 ... linking ... done.
ghci> fst $ runState dice_3d6 (mkStdGen 1)
[6,5,2]
ghci> fst $ runState dice_3d6 (mkStdGen 1)
[6,5,2]
ghci> fst $ runState dice_3d6 (mkStdGen 2)
[6,4,1]
ghci> fst $ runState dice_3d6 (mkStdGen 3)
[6,4,5]
在State StdGen
單子你可以寫這樣的東西:
rand :: (Random r) -> (r, r) -> State StdGen r
rand (x, y) = state (randomR (x, y))
randPoint :: State StdGen (Float, Float)
randPoint = do
x <- rand (-562, 562)
y <- rand (-288, 288)
return (x, y)
get100Points :: Int -> [(Float, Float)]
get100Points = fst . runState (sequence $ replicate 100 randPoint) . mkStdGen
我認爲給你100個隨機點沒有上面的那些類型類。但我在猜測你的三元函數相互遞歸在上面做了什麼。
發佈錯誤(全部)。 – chi 2014-10-31 12:44:21
和你指的類型/類。而且:如果格式化爲稍微更傳統的線寬,您的代碼將更具可讀性。 – leftaroundabout 2014-10-31 12:49:35
錯誤和格式化代碼有點更新後,不知道你指的是我指的類型/類是什麼? – user2999349 2014-10-31 12:52:57