我已经看到使用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
。
这是有道理的,因为迭代采用a -> a
函数,而我所拥有的是a -> m a
或类似的东西。所以,我真的不知道怎么去那里。
答案 0 :(得分:8)
我认为您正在寻找来自<=<
的{{1}}和>=>
。它们可以折叠在您使用Control.Monad
创建的列表中,以创建一个重要的操作。
尝试replicate
。