相关疑难解决方法(0)

固定空间和线性时间随机算法的迭代

我曾经问一个类似的问题一次.现在我会更具体.目的是学习一个Haskell习语来编写具有monadic结果的迭代算法.特别是,这可能对实现各种随机算法很有用,例如遗传算法等.

我写了一个示例程序,用Haskell中的这些算法表明了我的问题.它的完整来源是hpaste.

关键点是随机更新一个元素(因此结果是State StdGen或者其他一些monad):

type RMonad = State StdGen

-- An example of random iteration step: one-dimensional random walk.
randStep :: (Num a) => a -> RMonad a
randStep x = do
  rnd <- get
  let (goRight,rnd') = random rnd :: (Bool, StdGen)
  put rnd'
  if goRight
     then return (x+1)
     else return (x-1)
Run Code Online (Sandbox Code Playgroud)

然后需要更新许多元素,并多次重复该过程.这是一个问题.由于每一步都是monad action(:: a -> m a),重复多次,因此有效地组合这些动作很重要(快速忘记上一步).从我之前的问题中学到的东西(用折叠构成monad动作), seqdeepseq帮助组成monadic动作.所以我这样做:

-- Strict (?) iteration.
iterateM' …
Run Code Online (Sandbox Code Playgroud)

random performance profiling haskell

13
推荐指数
2
解决办法
1332
查看次数

标签 统计

haskell ×1

performance ×1

profiling ×1

random ×1