>>=
iterate
计算
[ return x , return x >>= step, return x >>= step >>= step, ... ]
你需要一个
迭代
:
-- This function does not work, but shows the principle we would
-- want from such a function.
iterateM :: Monad m => (a -> m a) -> a -> m [a]
iterateM f x = do
y <- f x
ys <- iterateM f y -- << this never terminates
return (y:ys)
但是,该变体不存在*,因为它不会终止,原因与
forM [1..] return
不终止。但是,如果将算法更改为
产生差异
replicateM
总和
这些差异
scanl
import Control.Monad (replicateM)
import System.Random (randomRIO)
step :: IO Int
step = randomRIO (-1, 1)
steps :: Int -> Int -> IO [Int]
steps n x = scanl (+) x <$> replicateM n step
在这种情况下,我们有有限的
step
s在
IO
扫描
*流媒体库中有一些变体
可以决定是否可以运行计算。
iterateM
可以在那里实现,例如
ConduitM
.