我已经看到使用iterate或replicate为了应用函数n时间的解决方案。但是,我没有设法在 State monad 中使用它。
此代码有效:
-- Stuff an empty game level with obstacles.
generateLevel :: Level -> State StdGen Level
generateLevel lvl =
placeRandomWall lvl >>= placeRandomWall >>= placeRandomWall
不出所料,这个也有效:
generateLevel :: Level -> State StdGen Level
generateLevel lvl =
placeRandomWall =<< placeRandomWall =<< placeRandomWall lvl
但是,这与以下内容不同:
generateLevel :: Level -> State StdGen Level
generateLevel lvl =
(placeRandomWall =<< placeRandomWall =<< placeRandomWall) lvl
最新的抱怨类型。因此,我不能foldl (=<<) id (relicate 42 placeRandomWall),也不能iterate。
这是有道理的,因为 iterate 需要一个a -> a函数,而我所拥有的是a -> m a或类似的东西。所以,我真的不知道如何从那里去。