Haskell 中generator 是啥意思, 咋使用

很久以前我弄了很久都没有成功, 刚才试了一下, 居然可以了.import System.Randommain = do gen \u0026lt;- getStdGen let (randomNum1, gen\u0026#39;) = next gen let (randomNum2, gen\u0026#39;\u0026#39;) = next gen\u0026#39; print $ 另外这样我觉得方便点.import System.Randommain = do randomNum1 \u0026lt;- randomRIO (10, 20) :: IO Int randomNum2 \u0026lt;- randomRIO (10, 20) :: IO Int print $
■网友
最近正好在学习Haskell,让我以有限的知识来回答下楼主的问题。首先楼主不必研究generator是什么了,generator就是个名字。下面正式进入回答-------------------------------------------楼主你的问题里next的type signature不对,完整的应该是这样子的:next :: RandomGen g =\u0026gt; g -\u0026gt; (Int, g)可见,类型变量g必须是RandomGen的instance. 那么RandomGen又是什么呢,我们来看一下:Prelude\u0026gt; :m +System.RandomPrelude System.Random\u0026gt; :i RandomGenclass RandomGen g wherenext :: g -\u0026gt; (Int, g)genRange :: g -\u0026gt; (Int, Int)split :: g -\u0026gt; (g, g)-- Defined in `System.Random\u0026#39;instance RandomGen StdGen -- Defined in `System.Random\u0026#39;先看最后一行,最后一行说StdGen这个类型是RandomGen的instance,然后就没有别的类型符合条件了。这就解释了为什么next 10会出类型错误了,10的类型不管是取Int还是Integer还是其他numerical的类型都不可能是RandomGen的instance。再看RandomGen的定义,其实就是规定了一个类型作为其instance必须实现的几个函数。据此我们可以自行定义某个类型为RandomGen的instance,比如Int:-- intGen.hsimport System.Randominstance RandomGen Int where next n = (n + 1, n + 1) genRange _ = (minBound, maxBound) split n = (n + 1, n + 2)载入ghci中看看结果如何:Prelude System.Random\u0026gt; :l intGen.hs Compiling Main ( intGen.hs, interpreted )Ok, modules loaded: Main.*Main System.Random\u0026gt; :i RandomGenclass RandomGen g where next :: g -\u0026gt; (Int, g) genRange :: g -\u0026gt; (Int, Int) split :: g -\u0026gt; (g, g) \t-- Defined in `System.Random\u0026#39;instance RandomGen Int -- Defined at intGen.hs:3:10instance RandomGen StdGen -- Defined in `System.Random\u0026#39;看倒数第二行,Int现在是RandomGen的instance了!!!我们来试下:*Main System.Random\u0026gt; next (10 :: Int)(11,11)当然这种随意的定义没什么用,Haskell引入RandomGen目的是为了生成随机数。可以用mkStdGen这个函数得到一个类型为StdGen的值,然后把该值传给random函数,返回一个所谓的随机数和一个新的类型为StdGen的值。注意random可以生成各种类型的随机数,比如Int,Bool,Double等等。*Main System.Random\u0026gt; :t mkStdGenmkStdGen :: Int -\u0026gt; StdGen*Main System.Random\u0026gt; next $ mkStdGen 10(399462,440154 40692)*Main System.Random\u0026gt; random(mkStdGen(11))::(Double, StdGen)(0.832860419682741,1124268239 2103410263)*Main System.Random\u0026gt; random(mkStdGen(11))::(Bool, StdGen)(True,480168 40692)


推荐阅读