我如何在函数中使用getStdGen

黄文wen

我是haskell的新手,尤其是Random类型,当我遇到此问题时,我正在浏览learnyouahaskell教程

import System.Random  

main = do  
    gen <- getStdGen  
    putStr $ take 20 (randomRs ('a','z') gen) 

但是,当我尝试在函数中使用它时,此操作失败(即)

genrandTF:: Int -> StdGen -> [Bool]
genrandTF number gen =  take number (randomRs (True, False) gen)

并通过调用

genrandTF 20 getStdGen

这是为什么?

-更新-

我得到的错误是

<interactive>:116:15:
    Couldn't match expected type `StdGen' with actual type `IO StdGen'
    In the second argument of `genrandTF', namely `(getStdGen)'
    In the expression: genrandTF 20 (getStdGen)

当我将其更改为IO StdGen类型时,由于收到以下消息,我无法编译:

No instance for (RandomGen (IO StdGen))
  arising from a use of `randomRs'
In the second argument of `take', namely
  `(randomRs (True, False) gen)'
In the expression: take number (randomRs (True, False) gen)
In an equation for `genrandTF':
    genrandTF number gen = take number (randomRs (True, False) gen)
CR Drost

这是初学者的常见错误。getStdGen是具有类型的值IO StdGen; 换句话说,它不是一个StdGen而是一个计算机程序,它在完成时将包含Haskell可以用作的内容StdGen

您将需要运行程序来获取StdGen(通过unsafePerformIO-顾名思义,这违反了Haskell中的几个安全保证),或者您需要将函数与程序结合以创建新程序。(通常,Haskell I / O是一堆与I / O操作交错的Haskell操作。)

做您想做的最简单的方法是:

fmap (genrandTF 20) getStdGen

将该Functor实例用于IO

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章