haskell将IO整数转换为Int System.Random.MWC [英] haskell Convert IO Int to Int System.Random.MWC
本文介绍了haskell将IO整数转换为Int System.Random.MWC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 unsafePerformIO
将 IO Int
从 System.Random.MWC
转换为 Int
.它确实可以在ghci中工作:
I would like to convert an IO Int
to Int
from System.Random.MWC
, using unsafePerformIO
. It does work in 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
但是在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)
它返回
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
推荐答案
这里真的不需要 unsafePerformIO
.只需更改 s
的类型以返回 IO Int
,然后使用do-notation或bind运算符将结果提供给 print
.
There's really no need for unsafePerformIO
here. Just change the type of s
to return IO Int
and use do-notation or the bind operator to feed the result to 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
或
main = do
gen <- createSystemRandom
print =<< s 30 gen
或
main = print =<< s 30 =<< createSystemRandom
这篇关于haskell将IO整数转换为Int System.Random.MWC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文