我想一个转换IO Int到Int从System.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 i386-unknown-linux):
make_exp (App _ (Coercion _))
Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug
Run Code Online (Sandbox Code Playgroud)
这里真的没有必要unsafePerformIO.只需更改s要返回的类型IO Int并使用do-notation或bind运算符将结果提供给print.
s :: Int -> GenIO -> IO Int
s k g = uniformR (0, k - 1) g
main :: IO ()
main = do
gen <- createSystemRandom
x <- s 30 gen
print x
Run Code Online (Sandbox Code Playgroud)
要么
main = do
gen <- createSystemRandom
print =<< s 30 gen
Run Code Online (Sandbox Code Playgroud)
要么
main = print =<< s 30 =<< createSystemRandom
Run Code Online (Sandbox Code Playgroud)