小编use*_*080的帖子

haskell system.random.mwc随机整数

我想使用库System.Random.MWC生成范围(0,30)中的随机整数.我可以使用库System.Random来做到这一点:

import System.Environment

import System.IO.Unsafe                                        

import System.Random

p :: Integer -> Integer

p n = unsafePerformIO (getStdRandom (randomR (0 , n)))

main :: IO()

main = do
        print $! (p 30)}
Run Code Online (Sandbox Code Playgroud)

但我对System.Random.MWC感到困惑.

random haskell integer

0
推荐指数
1
解决办法
499
查看次数

haskell将IO Int转换为Int System.Random.MWC

我想一个转换IO IntIntSystem.Random.MWC使用unsafePerformIO.它在ghci中有效:

Prelude System.Random.MWC System.IO.Unsafe> let p = unsafePerformIO(uniformR (0, 30) gen :: IO Int)

Prelude System.Random.MWC System.IO.Unsafe> p

11

Prelude System.Random.MWC System.IO.Unsafe> :t p

p :: Int
Run Code Online (Sandbox Code Playgroud)

但是在GHC

import System.Random.MWC
import System.IO.Unsafe  

main :: IO()
main = do
        gen <-createSystemRandom
        print $! s 30 gen

s :: Int-> GenIO -> Int
s !k g = unsafePerformIO(uniformR (0, k - 1) g)
Run Code Online (Sandbox Code Playgroud)

它返回

ghc: panic! (the 'impossible' happened)
(GHC version 7.6.3 for …
Run Code Online (Sandbox Code Playgroud)

io haskell

0
推荐指数
1
解决办法
173
查看次数

标签 统计

haskell ×2

integer ×1

io ×1

random ×1