gpt4 book ai didi

Haskell 随机生成

转载 作者:行者123 更新时间:2023-12-03 14:54:31 24 4
gpt4 key购买 nike

有人可以描述以下类型构造函数和函数是如何工作的吗?

type Rand a = State StdGen a  

getRandom :: (Random a) => Rand a
getRandom = get >>= (\r -> let (a,g) = random r in (put g) >> (return a))

runRand :: Int -> Rand a -> a
runRand n r = evalState r $ mkStdGen n

runRandIO :: Rand a -> IO a
runRandIO r = randomIO >>= (\rnd -> return $ runRand rnd r)

getRandoms :: (Random a) => Int -> Rand [a]
getRandoms n = mapM (\_ -> getRandom) [1..n]

最佳答案

让我们从头开始:

type Rand a = State StdGen a

这行告诉你 Rand aState 的类型同义词类型,其状态由 StdGen 给出其最终值为 a 类型.这将用于在每个随机数请求之间存储随机数生成器的状态。
getRandom 的代码可以转换为 do 表示法:
getRandom :: (Random a) => Rand a
getRandom = do
r <- get -- get the current state of the generator
let (a,g) = random r in do -- call the function random :: StdGen -> (a, StdGen)
put g -- store the new state of the generator
return a -- return the random number that was generated
runRand函数采用初始种子 n和一个值 r类型 Rand a (记住,它只是 State StdGen a 的同义词)。它使用 mkStdGen n 创建一个新的生成器并将其提供给 evalState r .函数 evalState只计算 State s a 的返回值类型,忽略状态。

同样,我们可以转换 runRandIO进入 do符号:
runRandIO :: Rand a -> IO a
runRandIO r = do
rnd <- randomIO -- generate a new random number using randomIO
return (runRand rnd r) -- use that number as the initial seed for runRand

最后, getRandoms取一个数字 n表示要生成的随机值的数量。它建立一个列表 [1..n]并申请 getRandom到列表中。注意 [1..n] 中的实际值未使用(您可以判断,因为 lambda 函数以 \_ -> ... 开头)。该列表只是为了包含正确数量的元素。由于 getRandom返回一个单子(monad)值,我们使用 mapM映射列表,这会导致状态(即 StdGen )通过对 getRandom 的每个调用正确线程化.

关于Haskell 随机生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com