Iteration of a randomized algorithm in fixed space and linear time

后端 未结 3 1604
半阙折子戏
半阙折子戏 2020-12-24 15:52

I used to ask a similar question once. Now I\'ll be more specific. The purpose is to learn a Haskell idiom to write iterative algorithms with monadic results. In particular,

3条回答
  •  星月不相逢
    2020-12-24 16:08

    Importing Control.Monad.State.Strict instead of Control.Monad.State yields a significant performance improvement. Not sure what you're looking for in terms of asymptotics, but this might get you there.

    Additionally, you get a performance increase by swapping the iterateM and the mapM so that you don't keep traversing the list, you don't have to hold on to the head of the list, and you don't need to deepseq through the list, but just force the individual results. I.e.:

    let end = flip evalState rnd $ mapM (iterateM iters randStep) start
    

    If you do so, then you can change iterateM to be much more idiomatic as well:

    iterateM 0 _ x = return x
    iterateM n f !x = f x >>= iterateM (n-1) f
    

    This of course requires the bang patterns language extension.

提交回复
热议问题